clear all
set more off

**************************************************
*Title: H_CHARLS_EOL_long
*Summary: converts data from the CHARLS to create the Harmonized CHARLS EOL, Version A
*Authors: Giacomo Rebellato, Jenny Wilkens, Drystan Phillips, & Jinkook Lee
*Date Created: May 2022
**************************************************

***define folder locations***
local inputw1 "||charls_wave1_data_folder||"
local inputw2 "||charls_wave2_data_folder||"
local stata "||H_CHARLS data folder||"
local lunar2solar "||solar_to_lunar_date_conversion_Mata_file_folder||"
local data "||save to folder||"

***define raw files***
*Wave 1 individual datasets
global wave_1_wp  "`inputw1'/work_retirement_and_pension.dta"
global wave_1_hi  "`inputw1'/household_income.dta"

*Wave 2 individual datasets
global wave_2_xt 	"`inputw2'/Exit_Interview.dta"
global wave_2_va  "`inputw2'/Verbal_Autopsy.dta"
global wave_2_wt  "`inputw2'/Weights.dta"
global wave_2_hi  "`inputw2'/Household_Income.dta"

*Wave 2 merged datasets (xt+va+wt)
global charls_exit_w2 "`inputw2'/charls_exit_w2.dta"

*Harmonized CHARLS*
global h_charls "`stata'/H_CHARLS_d.dta"

*solar to lunar date conversion Mata file
global lunar2solar "`lunar2solar'/lunar2solar.mmat"

***define programs***
*create special missing codes

***missing
***this is a program that creates special missing codes for HRS data
***
*** the program is called as follows
***		missing varlist, result(result)
***			where:
***				varlist - list of variables which should influence missing codes
***				result 	- name of variable, must be generated before program
***             wave - the wave of the variable being created which correctly assigns .m
***				[if] and [in] allow limitation of the program to a subsample using an if or in statement, both are optional
capture program drop missing
program define missing
syntax varlist [if] [in], result(varname) [wave(integer 99)]

marksample touse, novarlist // process if and in statements

quietly {
    if `wave' != 99 {
        local andinwavext & inw`wave'xt == 1
    }
    else {
        local andinwave 
    }
	foreach v of varlist `varlist' {
		replace `result' = .m if ((`v' == . | `v'==.m) `andinwave') & !inlist(`result',.d,.r) & (`touse') // * this is the lowest category
		}
	foreach v of varlist `varlist' {
		replace `result' = .d if `v' == .d & `result'!=.r & (`touse')
		}
	foreach v of varlist `varlist' {
		replace `result' = .r if `v' == .r & (`touse')
		}
	}
end



*lunar to solar date conversion (need to have "lunar2solar.mmat" file)
*! Version 1.0, Nov 07 2014, by Yafeng Wang, econyfwang@gmail.com
*! Chinese lunar to solar date transformation

program define lunar2solar
    version 10
    syntax varname(string) [if] [in], matfile(string) [leap GENerate(string)]
    marksample touse, strok
    if "`generate'" != "" {
        local newvar `generate'
    }
    else {
        local newvar `varlist'_solar
    }
    tempvar index mindex
    tempfile ls0 ls1
    qui {
    gen `index' = _n
    // leap == 0 sample
    preserve
    drop _all
    set obs 49949
    gen str8 `varlist' = ""
    gen str8 `newvar' = ""
    mata: lunar2solar("`matfile'", "`varlist'", "`newvar'", "")
    save "`ls0'"
    restore
    merge m:1 `varlist' using "`ls0'", gen(`mindex')
    drop if `mindex' == 2
    drop `mindex'
    replace `newvar' = "" if `touse' == 0
    // leap == 1 sample
    if ("`leap'" != "") {
        preserve
        drop _all
        set obs 1521
        gen str8 `varlist' = ""
        gen str8 `newvar' = ""
        mata: lunar2solar("`matfile'", "`varlist'", "`newvar'", "`leap'")
        save "`ls1'"
        restore
        merge m:1 `varlist' using "`ls1'", update replace gen(`mindex')
        drop if `mindex' == 2
        drop `mindex'
        replace `newvar' = "" if `touse' == 0
        }
    sort `index'
    }
end

mata: mata set matastrict on
mata: mata clear
mata: 
void function lunar2solar(string scalar matfile, string scalar lunarv, string scalar solarv, string scalar leap)
{
    string matrix ls, lsl, S, NS
    real scalar fh

    fh = fopen(matfile,"r")
    ls = fgetmatrix(fh)
    lsl = fgetmatrix(fh)
    fclose(fh)
    if (leap == "") {
        S = ls[.,2]
        NS = ls[.,1]
    }
    else {
        S = lsl[.,2]
        NS = lsl[.,1]
    }
    st_sstore(.,lunarv,S)
    st_sstore(.,solarv,NS)
}
end

*impute missing values
capture program drop charls_impute
program define charls_impute, sort
syntax varname [if] [in],  wave(int) [entry_var(varname) min_var(varname) max_var(varname) list extralistvars(passthru)]
    marksample touse, novarlist 
    
    qui gen `varlist'_i = .
    qui gen `varlist'_i_f = .
    qui gen `varlist'_i_neighbor = .
    
    *list covariates    
    local indepvars indepvars(ragender radagecat_i)
    
    *set min and max options
    if "`min_var'" != "" {
        local minopt min(`min_var') 
    }
    
    if  "`max_var'" != "" {
        local maxopt max(`max_var') 
    }
    
    local opteratoropt min_operator(>) max_operator(<)
    
    tempvar group
    if "`sepby'" != "" {
        qui egen `group' = group(`sepby'), label
    }
    else {
        qui gen `group' = 1
    }
    
    qui sum `group'
    forvalues g = 1 / `r(max)' { 
        
        if "`entry_var'" != "" {
            qui count if (!mi(`varlist') | `entry_var' == 0) & `touse' & `group' == `g'
        }
        else {
            qui count if !mi(`varlist') & `touse' & `group' == `g'
        }
        if `r(N)' > 0 {
            
            if "`sepby'" != "" {
                local groupname : label (`group') `g'
                di as result "**Imputing for: `groupname'"
            }
            
            if "`entry_var'" != "" {
                charls_entry_check `varlist', entryvar(`entry_var') `extralistvars' `minopt' `maxopt'
                di as result "*Assigning reported values when there is ownership"
                replace `varlist'_i = `varlist' if `touse' & `group' == `g' & `entry_var' == 1 & inw`wave'xt == 1 & !mi(`varlist') & mi(`varlist'_i) 
                qui replace `varlist'_i_f = 1 if `touse' & `group' == `g' & `entry_var' == 1 & inw`wave'xt == 1 & !mi(`varlist') & `touse' & mi(`varlist'_i_f)
                di

                di as result "*Assigning 0 values when there is no ownership"
                replace `varlist'_i = 0 if `touse' & `group' == `g' & `entry_var' == 0 & inw`wave'xt == 1 & mi(`varlist'_i) 
                qui replace `varlist'_i_f = 6 if `touse' & `group' == `g' & `entry_var' == 0 & inw`wave'xt == 1 & mi(`varlist'_i_f)
                di 
                
                *Estimate model
                local indepvarspec
            	foreach var of varlist `indepvars' {
            	    qui distinct `var'
            	    if `r(ndistinct)' > 2 {
            	        local indepvarspec `indepvarspec' i.`var'
            	    }
            	    else {
            	        local indepvarspec `indepvarspec' `var'
            	    }
            	}
            	
            	tempvar asinh prediction
                qui gen `asinh' = asinh(`varlist'_i) if `touse' & `group' == `g' & inw`wave'xt == 1
                qui regress `asinh' `indepvarspec' if `touse' & `group' == `g' & inw`wave'xt == 1
                qui predict `prediction' if `touse' & `group' == `g' & inw`wave'xt == 1, xb
                
                di as result "*Imputing when ownership is known"
                qui count if `touse' & `group' == `g' & `entry_var' == 1 & inw`wave'xt == 1 & !mi(`varlist'_i)
                if `r(N)' > 2 {
                    *di `"imputation_mixed `varlist' if `touse' & `group' == `g' & `entry_var' == 1 & inw`wave'xt == 1, harmonized(`varlist'_i) closeness(`prediction') id(mergeid) `maxopt' `opteratoropt' `minopt' exclude_flags(-1,2,3,5,6,7) `list' extralistvars(`indepvars' `extralistvars' `entry_var')"'
                    imputation_mixed `varlist' if `touse' & `group' == `g' & `entry_var' == 1 & inw`wave'xt == 1, harmonized(`varlist'_i) closeness(`prediction') id(mergeid) ///
                                        sort(mergeid) `maxopt' `opteratoropt' `minopt' exclude_flags(-1,2,3,5,6,7) `list' extralistvars(`indepvars' `extralistvars' `entry_var')
                }
                else {
                    qui count if `touse' & `group' == `g' & `entry_var' == 1 & inw`wave'xt == 1 & mi(`varlist'_i)
                    if `r(N)' > 0 {
                        di as error "The following observations with ownership need imputation but there is not more than one observations without missing values"
                        list mergeid `entry_var' `varlist' `min_var' `max_var' if `touse' & `group' == `g' & `entry_var' == 1 & inw`wave'xt == 1 & mi(`varlist'_i), noobs
                        qui replace `varlist'_i_f = -1 if `touse' & `group' == `g' & `entry_var' == 1 & inw`wave'xt == 1 & mi(`varlist'_i) & mi(`varlist'_i_f)
                        di
                    }
                }
            
                di as result "*Imputing when ownership is unknown"
                qui count if `touse' & `group' == `g' & inw`wave'xt == 1 & !mi(`varlist'_i) 
                if `r(N)' > 2 {
                    *di `"imputation_mixed `varlist' if `touse' & `group' == `g' & inw`wave'xt == 1 & mi(`entry_var'), harmonized(`varlist'_i) closeness(`prediction') id(mergeid) exclude_flags(-1,2,3,5,7) `list' extralistvars(`indepvars' `extralistvars') dknow"'
                    imputation_mixed `varlist' if `touse' & `group' == `g' & inw`wave'xt == 1, harmonized(`varlist'_i) closeness(`prediction') id(mergeid) ///
                                        sort(mergeid) exclude_flags(-1,2,3,5,7) `list' extralistvars(`indepvars' `extralistvars' `entry_var') dknow
                }
                else {
                    qui count if `touse' & `group' == `g' & mi(`entry_var') & inw`wave'xt == 1 & mi(`varlist'_i)
                    if `r(N)' > 0 {
                        di as error "The following observations need imputation but there is not more than one observations without missing values"
                        list mergeid  `entry_var' `varlist' if `touse' & `group' == `g' & mi(`entry_var') & inw`wave'xt == 1 & mi(`varlist'_i), noobs
                        qui replace `varlist'_i_f = -1 if `touse' & `group' == `g' & mi(`entry_var') & inw`wave'xt == 1 & mi(`varlist'_i) & mi(`varlist'_i_f)
                    }
                }
                di  
            }     
            else {
                 di as result "*Assigning reported values"
                replace `varlist'_i = `varlist' if `touse' & `group' == `g' & inw`wave'xt == 1 & !mi(`varlist') & mi(`varlist'_i) 
                qui replace `varlist'_i_f = 1 if `touse' & `group' == `g' & inw`wave'xt == 1 & !mi(`varlist') & mi(`varlist'_i_f)
                
                qui count if `touse' & `group' == `g' & inw`wave'xt == 1 & !mi(`varlist'_i)
                if `r(N)' > 2 {
                    *Estimate model
                    local indepvarspec
                	foreach var of varlist `indepvars' {
                	    qui distinct `var'
                	    if `r(ndistinct)' > 2 {
                	        local indepvarspec `indepvarspec' i.`var'
                	    }
                	    else {
                	        local indepvarspec `indepvarspec' `var'
                	    }
                	}
                	
                	tempvar asinh prediction
                    qui gen `asinh' = asinh(`varlist'_i) if `touse' & `group' == `g' & inw`wave'xt == 1
                    qui regress `asinh' `indepvarspec' if `touse' & `group' == `g' & inw`wave'xt == 1
                    qui predict `prediction' if `touse' & `group' == `g' & inw`wave'xt == 1, xb
                    
                    di as result "*Imputing"
                    imputation_mixed `varlist' if `touse' & `group' == `g' & inw`wave'xt == 1, harmonized(`varlist'_i) closeness(`prediction') id(hhidpn) /// 
                                       sort(hhidpn) `maxopt' `minopt' `opteratoropt' exclude_flags(-1,2,3,5,7) `list' extralistvars(`indepvars' `extralistvars') dknow
                }
                else if `r(N)' == 1 {
                    tempvar rand
    		        qui gen `rand' =  floor((2)*runiform()) if `touse' & `group' == `g' & inw`wave'xt == 1
    		        imputation_mixed `varlist' if `touse' & `group' == `g' & inw`wave'xt == 1, harmonized(`varlist'_i) closeness(`rand') id(hhidpn) /// 
                                       sort(hhidpn) `maxopt' `minopt' `opteratoropt' exclude_flags(-1,2,3,5,7) `list' extralistvars(`indepvars' `extralistvars') dknow
                }
                di                       
            }
        }
    }
    local anymiss
    local or
    foreach var of varlist `indepvars' {
        local anymiss `anymiss' `or' mi(`var')
        local or |
    }
    qui replace `varlist'_i_f = -2 if `touse' & inw`wave'xt == 1 & mi(`varlist'_i) & mi(`varlist'_i_f) & (`anymiss')
    
    imputation_summary_table `varlist'_i if `touse', `maxopt' `minopt' `opteratoropt'
    di
    
end
     capture program drop imputation_mixed
program define imputation_mixed, sort
syntax varname [if] [in], harmonized(varname) closeness(varname) id(varname) [min(varname) max(varname) min_operator(string) max_operator(string) ///
                          exclude_flags(string) outlier(passthru) noSeed list extralistvars(varlist) sort(varname) randsort dknow ]
	marksample touse, novarlist 
	
	if "`exclude_flags'" != "" {
	    local exclude_opt exclude_flags(`exclude_flags')
	    local exclude_cond & !inlist(`harmonized'_f,`exclude_flags')
	}
	else {
	    local exclude_opt
	    local exclude_cond
	}
	if "`extralistvars'" == "" {
	    local extralistvarsopt
	}
	else {
	    local extralistvarsopt extralistvars(`extralistvars')
	}	
	
	capture drop cell
    qui count if `touse' `exclude_cond' & mi(`harmonized')
    if `r(N)' > 0 {
        
        if "`seed'" == "" {
    	     set seed 123456789
        }
        	
        if "`sort'" != "" {
    	    local sort_option sort(`sort')
    	}
    	else if "`randsort'" == "randsort" {
    	    tempvar rand_sort
    	    qui gen `rand_sort' =  runiform()
    	    local sort_option sort(`rand_sort')
    	}
            
        if "`min'" != "" | "`max'" != "" {
        	qui egen cell = group(`min' `max') if `touse' `exclude_cond' & mi(`harmonized'), missing
            
        	sum cell, meanonly
        	forvalues i = 1/`r(max)' {
        	    if "`min'" != "" {
            		su `min' if cell == `i', meanonly
            		local bracket_min = r(mean)
            	}
            	else {
            	    local bracket_min = .
            	}
            	if "`max'" != "" {
            		su `max' if cell == `i', meanonly    
            		local bracket_max = r(mean)
            	}
            	else {
            	    local bracket_max = .
            	}
        		di as result "Reported min=`bracket_min' max=`bracket_max'"
        		
        		if "`bracket_min'" != "." {
        			if "`bracket_max'" != "." { // *max and min given
        			    if `bracket_min' == `bracket_max' {
        			        qui count if cell == `i' & `touse'
                            di as result "Number of observations with this about value:`r(N)'"
            			    replace `harmonized' = `min' if cell == `i' & `touse'
        				    qui replace `harmonized'_f = 2 if cell == `i' & `touse'
        				}
        				else {
        				    impute_mixed `harmonized' if `touse', closeness(`closeness') min(`bracket_min') min_operator(`min_operator') max(`bracket_max') max_operator(`max_operator') ///
        					imput_flag(`harmonized'_f) neighbor_flag(`harmonized'_neighbor) flag_value(2) cell(`i') `exclude_opt' `outlier' `list' `extralistvarsopt' `sort_option' id(`id')
        				}
        			}
        			else { // * only min given
        			    impute_mixed `harmonized' if `touse', closeness(`closeness') min(`bracket_min') min_operator(`min_operator') ///
    						imput_flag(`harmonized'_f) neighbor_flag(`harmonized'_neighbor) flag_value(3) cell(`i') `exclude_opt' `outlier' `list' `extralistvarsopt' `sort_option' id(`id')
        			}
        		}
        		else {
        			if "`bracket_max'" != "." { // * only max given
    					impute_mixed `harmonized' if `touse', closeness(`closeness') max(`bracket_max') max_operator(`max_operator') ///
    						imput_flag(`harmonized'_f) neighbor_flag(`harmonized'_neighbor) flag_value(2) cell(`i') `exclude_opt' `outlier' `list' `extralistvarsopt' `sort_option' id(`id')
        			}
        			else { // * neither max or min given
        			    if "`dknow'" == "" {
            				impute_mixed `harmonized' if `touse', closeness(`closeness') ///
            					imput_flag(`harmonized'_f) neighbor_flag(`harmonized'_neighbor) flag_value(5) cell(`i') `exclude_opt' `outlier' `list' `extralistvarsopt' `sort_option' id(`id')
            				}
            				else {
            				  impute_mixed `harmonized' if `touse', closeness(`closeness') ///
            					imput_flag(`harmonized'_f) neighbor_flag(`harmonized'_neighbor) flag_value(7) cell(`i') `exclude_opt' `outlier' `list' `extralistvarsopt' `sort_option' id(`id')  
            				}
        			}
        		}
        		
        		if "`list'" != "" {
        		    di as result "Imputed cases:"
            		list `id' `extralistvars' `closeness' `varlist' `min' `max' `harmonized' `harmonized'_f `harmonized'_neighbor if cell == `i' & `touse' & !mi(`harmonized'), noobs
            	}
            	di
        	}
            drop cell 
        }
        else {
            qui gen cell = 1 if  `touse' `exclude_cond' & mi(`harmonized')
            if "`dknow'" == "" {
                impute_mixed `harmonized' if `touse', closeness(`closeness') ///
        						   imput_flag(`harmonized'_f) neighbor_flag(`harmonized'_neighbor) flag_value(5) cell(1) `exclude_opt' `outlier' `list' `extralistvarsopt' `sort_option' id(`id')
        	}
        	else {
        	    impute_mixed `harmonized' if `touse', closeness(`closeness') ///
        						   imput_flag(`harmonized'_f) neighbor_flag(`harmonized'_neighbor) flag_value(7) cell(1) `exclude_opt' `outlier' `list' `extralistvarsopt' `sort_option' id(`id')
        	}
    	    if "`list'" != "" {
    	        di as result "Imputed cases:"
        		list `id' `extralistvars' `closeness' `varlist' `harmonized' `harmonized'_f `harmonized'_neighbor if cell == 1 & `touse' & !mi(`harmonized'), noobs
        	}
        	di
            drop cell
        }
        
        qui count if mi(`harmonized') & `touse' `exclude_cond'
    	if r(N) > 0 {
    		di as error "Imputed values were not assinged in the following `r(N)' cases:"
    		list `id' `varlist' `min' `max' `extralistvars' `harmonized' `harmonized'_f if ///
    				mi(`varlist') & mi(`harmonized') &  `touse' `exclude_cond', noobs
    		di		
    	}
    }
    else {
        di as text "no observations have missing values"
        di
    }
	
	
    
end

    
 capture program drop impute_mixed
program define impute_mixed, sort
syntax varname [if] [in],  closeness(varname) imput_flag(varname) neighbor_flag(varname) flag_value(integer) cell(integer) id(varname) ///
        [min(real 9999.999) max(real 9999.999) min_operator(string) max_operator(string) exclude_flags(string) outlier(real 100) list extralistvars(varlist) sort(varname)]

	marksample touse, novarlist
	
	capture drop hot
	capture drop `varlist'_i
	capture drop lower_n_value
	capture drop lower_n_closeness
	capture drop lower_n_id
	capture drop upper_n_value
	capture drop upper_n_closeness
	capture drop upper_n_id
	
	if `outlier' != 100 {
        _pctile `varlist', p(`outlier')
        local outlier_restric & `varlist' <= `r(r1)'
    }
	
	if `min' != 9999.999 {
	    *di as result "use min=`min'"
	    if `max' != 9999.999 {
	        *di as result "use max=`max'"
	        local hotcondition cell == `cell' | (`varlist' `min_operator' `min' & `varlist' `max_operator' `max' `outlier_restric')
	    }
	    else {
	        local hotcondition cell == `cell' | (`varlist' `min_operator' `min' & !mi(`varlist') `outlier_restric')
	    }
	}
	else {
	    if `max' != 9999.999 {
	        *di as result "use max=`max'"
	        local hotcondition cell == `cell' | (`varlist' `max_operator' `max' & !mi(`varlist') `outlier_restric')
	    }
	    else {
	        local hotcondition cell == `cell' | (!mi(`varlist') `outlier_restric')
	    }
	}
	
	if "`exclude_flags'" != "" {
	    local exclude_cond & !inlist(`imput_flag',`exclude_flags')
	}
	else {
	    local exclude_cond
	}
	
	qui gen hot = 1 if `touse' & (`hotcondition') `exclude_cond'
	
	qui count if hot == 1 & !mi(`varlist')
	local num_not_miss = r(N) 
	qui count if hot == 1 & mi(`varlist')
	local num_miss = r(N)
	di as res  "Number of observations without missing values:" `num_not_miss'
	di as res  "Number of observations with    missing values:" `num_miss' 
	if `num_miss' == 0 {
	    list `id' `extralistvars' `varlist' hot if cell == `cell'
	}
	
	if `num_miss' > 0 {
	    	if `num_not_miss' < 2 {
    		if `min' != 9999.999 {
        	    if `max' != 9999.999 {
        	        qui gen double `varlist'_i = .
        	        di as error "The following observations need imputation but there is not more than one observation with a value between the minimum and the maximum:"
        	        list `id' if hot == 1 & mi(`varlist'), noobs
        	        qui replace `imput_flag' = -1 if hot == 1 & mi(`varlist')
        	    }
        	    else {
        	        qui gen double `varlist'_i = .
        	        di as error "The following observations need imputation but there is not more than one observation with a value above the minimum:"
        	        list `id' if hot == 1 & mi(`varlist'), noobs
        	        qui replace `imput_flag' = -1 if hot == 1 & mi(`varlist')
        	    }
        	}
        	else {
        	    if `max' != 9999.999 {
        	        qui gen double `varlist'_i = .
        	        di as error "The following observations need imputation but there is not more than one observation below their maximum:"
        	        list `id' if hot == 1 & mi(`varlist'), noobs
        	        qui replace `imput_flag' = -1 if hot == 1 & mi(`varlist')
        	        di
        	    }
        	    else {
        	        qui gen double `varlist'_i = .
        	        di as error "The following observations need imputation but there is not more than one observation with a non-missing value:"
        	        list `id' if hot == 1 & mi(`varlist'), noobs
        	        qui replace `imput_flag' = -1 if hot == 1 & mi(`varlist')
        	        di
        	    }
        	}
        	qui replace `imput_flag' = `flag_value' if mi(`varlist') & !mi(`varlist'_i) 
    		drop `varlist'_i
    	}
	    else if `num_not_miss' < 50 {
	        di as text "There are fewer than 50 observations with reported values, covariates will not be used for this group."
	        sort hot `sort'
    		
    		qui gen lower_n_value = .
    		qui gen lower_n_id = ""
    		
    		qui gen upper_n_value = .
    		qui gen upper_n_id = ""
    		
    		local idformat : format `id'
    		format `idformat' lower_n_id upper_n_id `neighbor_flag'
    		
    		tempvar obs
    		gen `obs' = _n
    		qui sum `obs' if hot == 1 & !mi(`varlist')
    		local first = `r(min)'
    		local last = `r(max)'
   	
    		qui count if hot == 1
    		forvalues n = 1 / `r(N)' {
        		qui replace lower_n_value = `varlist'[_n-`n'] if !mi(`varlist'[_n-`n']) & hot[_n-`n'] == 1 & mi(lower_n_value) & hot == 1 & mi(`varlist')
        		qui replace lower_n_id = `id'[_n-`n'] if !mi(`varlist'[_n-`n']) & hot[_n-`n'] == 1 & mi(lower_n_id) & hot == 1 & mi(`varlist')
        		
        		qui replace upper_n_value = `varlist'[_n+`n'] if !mi(`varlist'[_n+`n']) & hot[_n+`n'] == 1 & mi(upper_n_value) & hot == 1 & mi(`varlist')
        		qui replace upper_n_id = `id'[_n+`n'] if !mi(`varlist'[_n+`n']) & hot[_n+`n'] == 1 & mi(upper_n_id) & hot == 1 & mi(`varlist')
        		
        		qui count if mi(lower_n_value) & hot == 1 & mi(`varlist') & _n > `first'
        		if r(N) == 0 {
        		    qui count if mi(upper_n_value) & hot == 1 & mi(`varlist') & _n < `last'
        		    if r(N) == 0 {
        		        continue, break
        		    }
        		}
        	}
    		
    		qui gen `varlist'_i = .
    		tempvar rand
    		qui gen `rand' =  floor((2)*runiform()) if hot == 1
    		qui replace `varlist'_i = lower_n_value if `rand' == 0 & !mi(lower_n_value) & !mi(upper_n_value) & mi(`varlist')
    		qui replace `varlist'_i = upper_n_value if `rand' == 1 & !mi(lower_n_value) & !mi(upper_n_value) & mi(`varlist')
    		qui replace `varlist'_i = lower_n_value if !mi(lower_n_value) & mi(upper_n_value) & mi(`varlist')
    		qui replace `varlist'_i = upper_n_value if mi(lower_n_value) & !mi(upper_n_value) & mi(`varlist')
    		
    		qui replace `neighbor_flag' = lower_n_id if `rand' == 0 & !mi(lower_n_value) & !mi(upper_n_value) & mi(`varlist')
    		qui replace `neighbor_flag' = upper_n_id if `rand' == 1 & !mi(lower_n_value) & !mi(upper_n_value) & mi(`varlist')
    		qui replace `neighbor_flag' = lower_n_id if !mi(lower_n_value) & mi(upper_n_value) & mi(`varlist')
    		qui replace `neighbor_flag' = upper_n_id if mi(lower_n_value) & !mi(upper_n_value) & mi(`varlist')
    		
    		qui replace `imput_flag' = `flag_value' if mi(`varlist') & !mi(`varlist'_i)
    		
    		if "`list'" == "list" {
    		    tempvar print
    		    qui egen `print' = seq() if hot == 1
    		    qui sum `print' if cell == `cell'
    		    if `r(N)' > 1 {
        		    local low_print_low = r(min) - 3
        		    local high_print_low = r(min) + 3 
        		    local low_print_high = r(max) - 3
        		    local high_print_high = r(max) + 3 
        		    di as result "Example Assignments:"
        		    list `id' `extralistvars' `varlist' lower_n_id lower_n_value upper_n_id upper_n_value if `print' >= `low_print_low' & `print' <= `high_print_low' , noobs sep(7)
                    list `id' `extralistvars' `varlist' lower_n_id lower_n_value upper_n_id upper_n_value if `print' >= `low_print_high' & `print' <= `high_print_high' , noobs sep(7)
                }
                else {
                    local low_print_low = r(min) - 3
        		    local high_print_low = r(min) + 3 
        		    di as result "Assignment:"
        		    list `id' `extralistvars' `varlist' lower_n_id lower_n_value upper_n_id upper_n_value if `print' >= `low_print_low' & `print' <= `high_print_low' , noobs sep(7)
                }
    		}
    		
    		replace `varlist' = `varlist'_i if mi(`varlist') & !mi(`varlist'_i)
    		
    		drop `varlist'_i
    		drop lower_n_value
        	drop lower_n_id
        	drop upper_n_value
        	drop upper_n_id
	    }
	    else {
    		sort hot `closeness' `sort'
    		
    		qui gen lower_n_value = .
    		qui gen lower_n_closeness = .
    		qui gen lower_n_id = ""
    		
    		qui gen upper_n_value = .
    		qui gen upper_n_closeness = .
    		qui gen upper_n_id = ""
    		
    		local idformat : format `id'
    		format `idformat' lower_n_id upper_n_id `neighbor_flag'
    		
    		tempvar obs
    		gen `obs' = _n
    		qui sum `obs' if hot == 1 & !mi(`closeness') & !mi(`varlist')
    		local first = `r(min)'
    		local last = `r(max)'
   	
    		qui count if hot == 1 & !mi(`closeness')
    		forvalues n = 1 / `r(N)' {
        		qui replace lower_n_value = `varlist'[_n-`n'] if !mi(`varlist'[_n-`n']) & hot[_n-`n'] == 1 & mi(lower_n_value) & hot == 1 & !mi(`closeness') & mi(`varlist')
        		qui replace lower_n_closeness = abs(`closeness'- `closeness'[_n-`n']) if !mi(`varlist'[_n-`n']) & hot[_n-`n'] == 1 & mi(lower_n_closeness) & hot == 1 & !mi(`closeness') & mi(`varlist')
        		qui replace lower_n_id = `id'[_n-`n'] if !mi(`varlist'[_n-`n']) & hot[_n-`n'] == 1 & mi(lower_n_id) & hot == 1 & !mi(`closeness') & mi(`varlist')
        		
        		qui replace upper_n_value = `varlist'[_n+`n'] if !mi(`varlist'[_n+`n']) & hot[_n+`n'] == 1 & mi(upper_n_value) & hot == 1 & !mi(`closeness') & mi(`varlist')
        		qui replace upper_n_closeness = abs(`closeness' - `closeness'[_n+`n']) if !mi(`varlist'[_n+`n']) & hot[_n+`n'] == 1 & mi(upper_n_closeness) & hot == 1 & !mi(`closeness') & mi(`varlist')
        		qui replace upper_n_id = `id'[_n+`n'] if !mi(`varlist'[_n+`n']) & hot[_n+`n'] == 1 & mi(upper_n_id) & hot == 1 & !mi(`closeness') & mi(`varlist')
        		
*        		if `n' > 4 {
*        		    di "first:`first'"
*        		    di "last:`last'"
*        		    list `id' `closeness' `varlist' lower_n_id lower_n_value upper_n_id upper_n_value if hot==1
*        		    di
*        		}
        		
        		qui count if mi(lower_n_value) & hot == 1 & !mi(`closeness') & mi(`varlist') & _n > `first' 
        		if r(N) == 0 {
        		    qui count if mi(upper_n_value) & hot == 1 & !mi(`closeness') & mi(`varlist') & _n < `last' 
        		    if r(N) == 0 {
        		        continue, break
        		    }
        		}
        	}
    		
    		qui gen `varlist'_i = .
    		tempvar rand
    		qui gen `rand' =  floor((2)*runiform()) if hot == 1
    		qui replace `varlist'_i = lower_n_value if lower_n_closeness < upper_n_closeness & !mi(lower_n_closeness) & !mi(upper_n_closeness) & mi(`varlist')
    		qui replace `varlist'_i = upper_n_value if upper_n_closeness < lower_n_closeness & !mi(lower_n_closeness) & !mi(upper_n_closeness) & mi(`varlist')
    		qui replace `varlist'_i = lower_n_value if lower_n_closeness == upper_n_closeness & `rand' == 0 & !mi(lower_n_closeness) & !mi(upper_n_closeness) & mi(`varlist')
    		qui replace `varlist'_i = upper_n_value if upper_n_closeness == lower_n_closeness & `rand' == 1 & !mi(lower_n_closeness) & !mi(upper_n_closeness) & mi(`varlist')
    		qui replace `varlist'_i = lower_n_value if !mi(lower_n_closeness) & mi(upper_n_closeness) & mi(`varlist')
    		qui replace `varlist'_i = upper_n_value if mi(lower_n_closeness) & !mi(upper_n_closeness) & mi(`varlist')
    		
    		qui replace `neighbor_flag' = lower_n_id if lower_n_closeness < upper_n_closeness & !mi(lower_n_closeness) & !mi(upper_n_closeness) & mi(`varlist')
    		qui replace `neighbor_flag' = upper_n_id if upper_n_closeness < lower_n_closeness & !mi(lower_n_closeness) & !mi(upper_n_closeness) & mi(`varlist')
    		qui replace `neighbor_flag' = lower_n_id if lower_n_closeness == upper_n_closeness & `rand' == 0 & !mi(lower_n_closeness) & !mi(upper_n_closeness) & mi(`varlist')
    		qui replace `neighbor_flag' = upper_n_id if upper_n_closeness == lower_n_closeness & `rand' == 1 & !mi(lower_n_closeness) & !mi(upper_n_closeness) & mi(`varlist')
    		qui replace `neighbor_flag' = lower_n_id if !mi(lower_n_closeness) & mi(upper_n_closeness) & mi(`varlist')
    		qui replace `neighbor_flag' = upper_n_id if mi(lower_n_closeness) & !mi(upper_n_closeness) & mi(`varlist')	
    		
    		qui replace `imput_flag' = `flag_value' if mi(`varlist') & !mi(`varlist'_i)
    		
    		if "`list'" == "list" {
    		    tempvar print
    		    qui egen `print' = seq() if hot == 1
    		    qui sum `print' if cell == `cell'
    		    if `r(N)' > 1 {
        		    local low_print_low = r(min) - 3
        		    local high_print_low = r(min) + 3 
        		    local low_print_high = r(max) - 3
        		    local high_print_high = r(max) + 3 
        		    di as result "Example Assignments:"
        		    list `id' `extralistvars' `closeness' `varlist' lower_n_id lower_n_value lower_n_closeness upper_n_id upper_n_value upper_n_closeness if `print' >= `low_print_low' & `print' <= `high_print_low' , noobs sep(7)
                    list `id' `extralistvars' `closeness' `varlist' lower_n_id lower_n_value lower_n_closeness upper_n_id upper_n_value upper_n_closeness if `print' >= `low_print_high' & `print' <= `high_print_high' , noobs sep(7)
                }
                else {
                    local low_print_low = r(min) - 3
        		    local high_print_low = r(min) + 3 
        		    di as result "Assignment:"
        		    list `id' `extralistvars' `closeness' `varlist' lower_n_id lower_n_value lower_n_closeness upper_n_id upper_n_value upper_n_closeness if `print' >= `low_print_low' & `print' <= `high_print_low' , noobs sep(7)
                }
    		}
    		
    		replace `varlist' = `varlist'_i if mi(`varlist') & !mi(`varlist'_i)
    		
    		drop `varlist'_i
    		drop lower_n_value
        	drop lower_n_closeness
        	drop lower_n_id
        	drop upper_n_value
        	drop upper_n_closeness
        	drop upper_n_id
        }
	}
	else {
		di as res  "No missing values for respondents in this cell"
	}
	drop hot
end
capture program drop charls_entry_check
program define charls_entry_check
syntax varname [if] [in], entryvar(varname) [extralistvars(varlist)]
    marksample touse, novarlist 
    qui count if `entryvar' == 1 & `varlist' == -1 & `touse'
    if  `r(N)' > 0 {
        di
        di as error "Warning: `r(N)' respondents were given ownership for `varlist' but have -1 missing vales"
        list `extralistvars' `entryvar' `varlist' if `entryvar' == 1 & `varlist' == -1, noobs
    }
    qui count if mi(`entryvar') & `varlist' == -1 & `touse'
    if  `r(N)' > 0 {
        di
        di as error "Warning: `r(N)' respondents were not assigned an ownership value for `varlist' but have -1 missing vales"
        list `extralistvars' `entryvar' `varlist' if mi(`entryvar') & `varlist' == -1, noobs
    }
    
end
    capture program drop imputation_summary_table
program define imputation_summary_table
syntax varname [if] [in], [min(varname) max(varname)  min_operator(string) max_operator(string)]
    marksample touse, novarlist 
    
    capture matrix drop B
    capture matrix drop C
    qui count if `varlist'_f == 1 & `touse'
    if `r(N)' > 0 {
        marg_distributions `varlist' if `varlist'_f == 1 & `touse', flag(`varlist'_f)
        matrix B = r(horizontal)
    }
    qui count if `varlist'_f == 6 & `touse'
    if `r(N)' > 0 {
        marg_distributions `varlist' if `varlist'_f == 6 & `touse', flag(`varlist'_f)
        matrix C = r(horizontal)
        local ownership yes 
    }
    else {
        local ownership no
    }
    marg_distributions `varlist' if inlist(`varlist'_f,1,6) & `touse', flag(`varlist'_f)
    matrix D = r(horizontal)
    
    
    capture confirm matrix B
    if !_rc {
        capture confirm matrix C
        if !_rc {
            matrix A = B[1...,8..8],B[1...,1..7] \ C[1...,8..8],C[1...,1..7] \ D[1...,8..8],D[1...,1..7]
            matrix rownames A = "CONTINUOUS" "NO OWNERSHIP" "All reported"
            matlist A, nodotz cspec(& %15s | %10.0fc & %10.1f & %10.1f & %10.2f & %10.1f & %10.1f & %10.1f & %10.1f &) rspec( & - & - - ) title("Reported Values")
        }
        else {
            matrix A = B[1...,8..8],B[1...,1..6]
            matrix rownames A = "CONTINUOUS"
            matlist A, nodotz cspec(& %15s | %10.0fc & %10.1f & %10.1f & %10.2f & %10.1f & %10.1f & %10.1f &) rspec( & - - ) title("Reported Values")
        }
    }
    else {
        capture confirm matrix C
        if !_rc {
            matrix A = C[1...,8..8],C[1...,1..7]
            matrix rownames A = "NO OWNERSHIP"
            matlist A, nodotz cspec(& %15s | %10.0fc & %10.1f & %10.1f & %10.2f & %10.1f & %10.1f & %10.1f & %10.1f &) rspec( & - - ) title("Reported Values")
        }
    }

    capture matrix drop B
    local rspec -
    qui count if `touse' & inlist(`varlist'_f,2,3)
    if `r(N)' > 0 {
        if "`min'" != "" | "`max'" != "" {
            tempvar cell
            qui count if `touse' & `varlist'_f == 2
            if `r(N)' > 0 {
                qui egen `cell' = group(`min' `max') if `touse' & `varlist'_f == 2, missing
                matrix B = [.z,.z,.z,.z,.z,.z,.z,.z]
                matrix rowname B = "CLOSED BRACKETS"
                local rspec `rspec' -
                su `cell', meanonly
            	forvalues i = 1 / `r(max)' {
            		su `min' if `cell' == `i', meanonly
            		local bracket_min = r(mean)
            		su `max' if `cell' == `i', meanonly    
            		local bracket_max = r(mean)
                    if "`bracket_max'" != "." {
            			if "`bracket_min'" == "." {
                            marg_distributions `varlist' if `cell' == `i' & `touse', flag(`varlist'_f)
                            matrix C = r(horizontal)
                            matrix rownames C = "Imputed values"
                            matrix roweq C = "0-`bracket_max'"
                            matrix B = B \ C
                            qui count if `varlist'_f == 1 & `varlist' `max_operator' `bracket_max' & `touse'
                            if `r(N)' > 0 {
                                marg_distributions `varlist' if `varlist'_f == 1 & `varlist' `max_operator' `bracket_max' & `touse', flag(`varlist'_f)
                                matrix C = r(horizontal)
                            }
                            else {
                                matrix C = [.,.,.,.,.,.,.,0]
                            }
                            matrix rownames C = "Donor values"
                            matrix roweq C = "0-`bracket_max'"
                            matrix B = B \ C
                            local rspec `rspec' & &
                        }
                    }
                }
                su `cell', meanonly
                forvalues i = 1 / `r(max)' {
            		su `min' if `cell' == `i', meanonly
            		local bracket_min = r(mean)
            		su `max' if `cell' == `i', meanonly    
            		local bracket_max = r(mean)
                    if "`bracket_max'" != "." {
            			if "`bracket_min'" != "." {
                            marg_distributions `varlist' if `cell' == `i' & `touse', flag(`varlist'_f)
                            matrix C = r(horizontal)
                            matrix rownames C = "Imputed values"
                            matrix roweq C = "`bracket_min'-`bracket_max'"
                            matrix B = B \ C
                            qui count if `varlist'_f == 1 & `varlist' `min_operator' `bracket_min' & `varlist' `max_operator' `bracket_max' & `touse'
                            if `r(N)' > 0 {
                                marg_distributions `varlist' if `varlist'_f == 1 & `varlist' `min_operator' `bracket_min' & `varlist' `max_operator' `bracket_max' & `touse', flag(`varlist'_f)
                                matrix C = r(horizontal)
                            }
                            else {
                                matrix C = [.,.,.,.,.,.,.,0]
                            }
                            matrix rownames C = "Donor values"
                            matrix roweq C = "`bracket_min'-`bracket_max'"
                            matrix B = B \ C
                            local rspec `rspec' & &
                        }
                    }
                }
            }
            qui count if `touse' & `varlist'_f == 3
            if `r(N)' > 0 {
                tempvar cell
                qui egen `cell' = group(`min' `max') if `touse' & `varlist'_f == 3, missing
                matrix C = [.z,.z,.z,.z,.z,.z,.z,.z]
                matrix rowname C = "OPEN BRACKETS"
                local rspec `rspec' -
                capture confirm matrix B
                if !_rc {
                    matrix B = B\C
                }
                else {
                    matrix B = C
                }
                su `cell', meanonly
            	forvalues i = 1/`r(max)' {
            		su `min' if `cell' == `i', meanonly
            		local bracket_min = r(mean)
                    marg_distributions `varlist' if `cell' == `i' & `touse', flag(`varlist'_f)
                    matrix C = r(horizontal)
                    matrix rownames C = "Imputed values"
                    matrix roweq C = "`bracket_min'+"
                    matrix B = B \ C
                    qui count if `varlist'_f == 1 & `varlist' `min_operator' `bracket_min' & `touse'
                    if `r(N)' > 0 {
                        marg_distributions `varlist' if `varlist'_f == 1 & `varlist' `min_operator' `bracket_min' & `touse', flag(`varlist'_f)
                        matrix C = r(horizontal)
                    }
                    else {
                        matrix C = [.,.,.,.,.,.,.,0]
                    }
                    matrix rownames C = "Donor values"
                    matrix roweq C = "`bracket_min'+"
                    matrix B = B \ C
                    local rspec `rspec' & &
                }
            }
        }
    }
    
    qui count if `varlist'_f == 5 & `touse'
    if `r(N)' > 0 {
        matrix C = [.z,.z,.z,.z,.z,.z,.z,.z]
        matrix rowname C = "NO BRACKET/VALUE"
        local rspec `rspec' -
        capture confirm matrix B
        if !_rc {
            matrix B = B\C
        }
        else {
            matrix B = C
        }
        marg_distributions `varlist' if `varlist'_f == 5 & `touse', flag(`varlist'_f)
        matrix C = r(horizontal)
        matrix rownames C = "Imputed values"
        matrix B = B \ C
        marg_distributions `varlist' if `varlist'_f == 1 & `touse', flag(`varlist'_f)
        matrix C = r(horizontal)
        matrix rownames C = "Donor values"
        matrix B = B \ C
        local rspec `rspec' & &
    }
    qui count if `varlist'_f == 7 & `touse'
    if `r(N)' > 0 {
        matrix C = [.z,.z,.z,.z,.z,.z,.z,.z]
        matrix rowname C = "DK"
        local rspec `rspec' -
        capture confirm matrix B
        if !_rc {
            matrix B = B\C
        }
        else {
            matrix B = C
        }
        marg_distributions `varlist' if `varlist'_f == 7 & `touse', flag(`varlist'_f)
        matrix C = r(horizontal)
        matrix rownames C = "Imputed values"
        matrix B = B \ C
        marg_distributions `varlist' if inlist(`varlist'_f,1,6) & `touse', flag(`varlist'_f)
        matrix C = r(horizontal)
        matrix rownames C = "Donor values"
        matrix B = B \ C
        local rspec `rspec' & &
    }
    
    capture confirm matrix B
    if !_rc {
        if "`ownership'" == "yes" {
            matrix A = B[1...,8..8],B[1...,1..7]
            matrix colnames A = n mean sd skewness median min max ownership
            matlist A, nodotz cspec(& %20s | %10.0fc & %10.1f & %10.1f & %10.2f & %10.1f & %10.1f & %10.1f & %10.1f &) rspec( `rspec' - ) title("Imputed Values")
        }
        else {
            matrix A = B[1...,8..8],B[1...,1..6]
            matrix colnames A = n mean sd skewness median min max
            matlist A, nodotz cspec(& %20s | %10.0fc & %10.1f & %10.1f & %10.2f & %10.1f & %10.1f & %10.1f &) rspec( `rspec' - ) title("Imputed Values")
        }
    }
end
    capture program drop marg_distributions
program define marg_distributions, rclass
syntax varname [if] [in], flag(varname)
    marksample touse, novarlist
    
    qui sum `varlist' if `touse',d
    matrix A_ = [`r(mean)' \ `r(sd)' \ `r(skewness)' \ `r(p50)' \ `r(min)' \ `r(max)' ]
    
    qui count if `touse' & (`flag' == 6 | (inlist(`flag',7,9) & `varlist' == 0))
    local num `r(N)'
    qui count if `touse' & !mi(`varlist')
    local den `r(N)'
    local per = ((`den'-`num')/`den')*100
    matrix A_ = A_ \ [`per']
    matrix A_ = A_ \ [`den']
    
    matrix colnames A_ = "`varlist'" 
    matrix rownames A_ = mean sd skewness median min max ownership n
    *matrix list A_, noheader
    
    matrix B_ = A_'
    *matlist B_, nodotz noheader cspec(& %15s | %10.2fc & %10.2fc & %10.4f & %10.0f & %10.2f &) rspec( & - & )
    return matrix vertical = A_
    return matrix horizontal = B_
    
end

*count distinct observations
ssc install distinct

********************************************************************************************************************
********************************************************************************************************************

***adjust ID for wave 1 pensions***
tempfile w1_wp
use "$wave_1_wp"

rename ID ID_w1

save "`w1_wp'"
global w1_wp `w1_wp'
clear

***adjust ID for wave 1 income***
tempfile w1_hi
use "$wave_1_hi"

rename householdID householdID_w1

save "`w1_hi'"
global w1_hi `w1_hi'
clear

********************************************************************************************************************
********************************************************************************************************************

****load full set of CHARLS respondents***
use ID householdID hhid pnc pn ID_w1 householdID_w1 communityID ///
	  inw1 inw2 inw3 inw4 ragender ///
		c2009cpindex c2010cpindex c2011cpindex c2012cpindex c2013cpindex c2014cpindex ///
		c2015cpindex c2016cpindex c2017cpindex c2018cpindex using "$h_charls"
gen in_charls = 1

********************************************************************************************************************
********************************************************************************************************************



***wave status: response indicator***
label define inwxt ///
   0 "0.nonresp" ///
   1 "1.resp,deceased"
   
***who interviewed***
label define relate ///
	1 "1.spouse" ///
	2 "2.child" ///
	3 "3.other relative" ///
	4 "4.other non-relative" ///
	.q ".q:not asked this wave" 
	
***age flag***
label define ageflag ///
	0 "0.reported/calculated age used" ///
	1 "1.month & year used" ///
	2 "2.only year used"

***death location***
label define locate ///
	1 "1.private home" ///
	2 "2.hospital" ///
	3 "3.nursing home" ///
	4 "4.hospice" ///
	5 "5.other" ///
	.q ".q:not asked this wave"
	
***where living***
label define living ///
	0 "0.not living in nursing home" ///
	1 "1.living in nursing home" 

***death expected***
label define expect ///
	1 "1.expected" ///
	2 "2.unexpected" ///
	3 "3.other"

***lunar/solar flag
label define lunarsolar ///
	1 "1.solar calendar" ///
	2 "2.lunar calendar"
	
	
***death duration***
label define duration ///
	1 "1.suddenly/1-2 hours" ///
	2 "2.less than 1 day" ///
	3 "3.less than 1 week" ///
	4 "4.less than 1 month" ///
	5 "5.less than 1 year" ///
	6 "6.more than 1 year" ///
	.q ".q:not asked this wave" ///
	.s ".s:skipped"

**married or partnered***
label define yesnomarr ///
	0 "0.not married nor partnered" ///
	1 "1.married or partnered" ///


***interview flag***
label define ivwflag ///
	1 "1.month and year used" ///
	2 "2.only year used" 


***death cause original***
label define causes ///
	1 "1.infectious, parasitic diseases" ///
	2 "2.cancer" ///
	3 "3.nutritional, endocrine disorders" ///
	4 "4.circulatory system diseases" ///
	5 "5.respiratory disorders" ///
	6 "6.gastrointestinal disorders" ///
	7 "7.renal disorders" ///
	8 "8.mental, nervous system disorders" ///
	9 "9.external causes of death" ///
	10 "10.unknown/natural causes/other" ///
	11 "11.multiple causes of death" ///
	.i ".i:invalid responses" ///
	.d ".d:don't know" ///
	.r ".r:refuse to answer"
	

***death cause harmonized***
label define grpcaus ///
	1 "1.cancer" /// 
	2 "2.cardiovascular" ///
	3 "3.other" ///
	.i ".i:invalid responses" ///
	.d ".d:don't know" ///
	.r ".r:refuse to answer"

	
	

*set wave number
local wv=2
local pre_wv=1



****merge with wave 2 harmonized CHARLS data***
local demogxt_w2_hcharls r1iwy r2iwy radyear radmonth rabyear rabmonth r1agey
merge 1:1 ID using "$h_charls", keepusing(`demogxt_w2_hcharls') nogen

*****merge with wave 2 CHARLS Weights***
local demogxt_w2_wt iyear imonth
merge 1:m ID using "$wave_2_wt", keepusing(`demogxt_w2_wt')

drop if _merge==2
drop _merge

*****merge with wave 2 CHARLS Exit Interview***
local demogxt_w2_xt exb001_1 exb001_2 exb002 exb003 exb003_1 exb005 exb009 exb010 exb010_1 exb011
merge 1:1 ID using "$wave_2_xt", keepusing(`demogxt_w2_xt')

***Generate died variable***
gen died = 0
replace died = 1 if _merge==3
drop _merge


*****merge with wave 2 CHARLS Verbal Autopsy***
local demogxt_w2_va va2a110 va3a300 va3a300_1 va3a300_2 va3a310 vas42
merge 1:1 ID using "$wave_2_va", keepusing(`demogxt_w2_va') nogen



****In exit interview***                
**wave 2 respondent in exit interview
gen inw`wv'xt = .
replace inw`wv'xt = 0 if died==0 // if inw2xt==1 | inw3xt==1 [... Add waves]
replace inw`wv'xt = 1 if died==1
label variable inw`wv'xt "inw`wv'xt: r in w`wv' exit interview"
label value inw`wv'xt inwxt
drop died


***Last completed core interview***
**wave 2 respondent last completed core interview
gen ralstcore = .
replace ralstcore = 1 if inw1==1 & inw`wv'xt==1
label variable ralstcore "ralstcore: r last completed core interview wave"


***year of last completed core interview***
*wave 2 respondent year of last completed core interview (Note: add forvalues loop in next wave)
gen ralstcorey = .
replace ralstcorey = r1iwy if ralstcore==1 & inlist(r1iwy,2011,2012)
label variable ralstcorey "ralstcorey: r last completed core interview year"


***Interview Month***
*wave 2 respondent exit interview month
gen raxtiwm = .
destring imonth iyear, replace
missing imonth if inw`wv'xt==1, result(raxtiwm) 
replace raxtiwm = imonth if inrange(imonth,1,12)
label variable raxtiwm "raxtiwm: r exit interview month"


****Interview year***
*wave 2 respondent exit interview year
gen raxtiwy = .
missing iyear if inw`wv'xt==1, result(raxtiwy) 
replace raxtiwy = iyear if inrange(iyear,1990,2020)
label variable raxtiwy "raxtiwy: r exit interview year"


***Death year and month
*wave 2 respondent death year
gen raxyear=.
missing radyear if inw`wv'xt==1, result(raxyear)
replace raxyear=radyear if inw`wv'xt==1
replace raxyear= .i if raxyear>raxtiwy & !mi(raxyear) & !mi(raxtiwy)
label variable raxyear "raxyear: r death year"
*wave 2 respondent death month
gen raxmonth=.
missing radmonth if inw`wv'xt==1, result(raxmonth)
replace raxmonth=radmonth if inw`wv'xt==1
replace raxmonth= .i if raxyear==raxtiwy & raxmonth>raxtiwm & !mi(raxmonth) & !mi(raxtiwm)
label variable raxmonth "raxmonth: r death month"
*wave 2 flag variable for lunar/solar date
gen raxdatef=.
missing exb002 if inw`wv'xt==1, result(raxdatef)
replace raxdatef = exb002 if !mi(exb002) & inw`wv'xt==1
label variable raxdatef "raxdatef: flag variable for solar/lunar calendar date"
label values raxdatef lunarsolar



***Age at death***
*wave 2 respondent age at death 

gen deathage = .
missing rabyear rabmonth raxyear raxmonth if inw`wv'xt==1, result(deathage)
replace deathage = .m if (raxyear==.m | raxmonth==.m | rabyear==.m | rabmonth==.m) & inw`wv'xt==1
replace deathage = .x if (rabyear==.x | rabmonth==.x) & inw`wv'xt==1
replace deathage = .d if (rabyear==.d | rabmonth==.d) & inw`wv'xt==1
replace deathage = .i if (rabyear==.i) & inw`wv'xt==1
replace deathage = raxyear - rabyear if !mi(rabyear) & !mi(raxyear) & inw`wv'xt==1
replace deathage = deathage + ((raxmonth - rabmonth)/12) if !mi(rabmonth) & !mi(raxmonth) & inw`wv'xt==1

gen radage = .
missing rabyear rabmonth raxyear raxmonth if inw`wv'xt==1, result(radage)
replace radage = .m if (raxyear==.m | raxmonth==.m | rabyear==.m | rabmonth==.m) & inw`wv'xt==1
replace radage = .x if (rabyear==.x | rabmonth==.x) & inw`wv'xt==1
replace radage = .d if (rabyear==.d | rabmonth==.d) & inw`wv'xt==1
replace radage = .i if (rabyear==.i | raxyear==.i | raxmonth==.i) & inw`wv'xt==1
replace radage = floor(deathage) if !mi(deathage) & inw`wv'xt==1
label variable radage "radage: r age at death"
drop deathage

*wave 2 respondent age at death flag
gen radagef = .
replace radagef = 1 if inrange(rabmonth,1,12) & inrange(raxmonth,1,12) & inw`wv'xt==1
replace radagef = 2 if (mi(rabmonth) | mi(raxmonth)) & inw`wv'xt==1
replace radagef = .m if inlist(radage,.m,.d,.r,.x,.i) & inw`wv'xt==1
label variable radagef "radagef: r flag age at death"
label values radagef ageflag

***Death location***
*wave 2 respondent death location
gen radloc = .
missing exb003 if inw`wv'xt==1, result(radloc) 
replace radloc = 1 if exb003==3
replace radloc = 2 if exb003==1
replace radloc = 5 if exb003==5
label variable radloc "radloc: r death location"
label values radloc locate


***Whether lived in nursing home prior to death***
*wave 2 respondent whether lived in nursing home prior to death 
gen radlivnh = .
missing exb005 if inw`wv'xt==1, result(radlivnh) 
replace radlivnh = 0 if inlist(exb005,1,3)
replace radlivnh = 1 if exb005==2
label variable radlivnh "radlivnh: r whether lived in nursing home prior to death"
label values radlivnh living


***Whether death was expected***
*wave 2 respondent whether death expected
gen radexpec = .
missing exb009 if inw`wv'xt==1, result(radexpec) 
replace radexpec = exb009 if inlist(exb009,1,2,3) 
label variable radexpec "radexpec: r death expected"
label values radexpec expect


***Time from death to interview, months***
*wave 2 respondent time from death to interview,months
gen radtoivwm = .
missing raxmonth raxyear raxtiwm raxtiwy if inw`wv'xt==1, result(radtoivwm) 
replace radtoivwm = .m if (raxyear==.m | raxmonth==.m) & inw`wv'xt==1
replace radtoivwm = .x if (raxyear==.x | raxmonth==.x) & inw`wv'xt==1
replace radtoivwm = .i if (raxyear==.i | raxmonth==.i) & inw`wv'xt==1
replace radtoivwm = .d if raxmonth==.d & inw`wv'xt==1
replace radtoivwm = (raxtiwy - raxyear) * 12 if !mi(raxtiwy) & !mi(raxyear) & inw`wv'xt==1
replace radtoivwm = (raxtiwm - raxmonth) + radtoivwm if !mi(radtoivwm) & !mi(raxtiwm) & !mi(raxmonth) & inw`wv'xt==1
replace radtoivwm = .i if inrange(radtoivwm,-100,-1) & inw`wv'xt==1
label variable radtoivwm "radtoivwm: r time between death and exit ivw, months"


***Time from death to interview, years***
*wave 2 respondent time from death to interview, years
gen radtoivwy = .
missing radtoivwm if inw`wv'xt==1, result(radtoivwy) 
replace radtoivwy = .m if radtoivwy==. & inw`wv'xt==1
replace radtoivwy = radtoivwm/12 if !mi(radtoivwm) & inw`wv'xt==1
replace radtoivwy = .i if radtoivwm==.i & inw`wv'xt==1
label variable radtoivwy "radtoivwy: r time between death and exit ivw, years"

*wave 2 respondent time from death to interview years flag
gen radtoivwf = .
replace radtoivwf = 1 if ((!mi(raxmonth) & !mi(raxtiwm)) | mi(radtoivwm)) & inw`wv'xt==1
replace radtoivwf = 2 if (mi(raxmonth) | mi(raxtiwm)) & inw`wv'xt==1
replace radtoivwf = .m if inlist(radtoivwy,.d,.r,.m,.i) & inw`wv'xt==1
label variable radtoivwf "radtoivwf: r flag time between death and exit ivw"
label values radtoivwf ivwflag


***Duration of final illness***
*wave 2 respondent duration final illness
gen raddur = .
missing exb010 if inw`wv'xt==1, result(raddur)
replace raddur = exb010 if inrange(exb010,1,6) & inw`wv'xt==1
label variable raddur "raddur: r duration final illness/death"
label values raddur duration

*wave 2 respondent duration final illness in days (w/ verbal autopsy variables)
gen raddurd = .
missing va3a300 va3a300_1 va3a300_2 if inw`wv'xt==1, result(raddurd)
replace raddurd = .d if va3a300==3 & inw`wv'xt==1
replace raddurd = va3a300_1 if va3a300==1 & inw`wv'xt==1
replace raddurd = (va3a300_2)*7 if va3a300==2 & inw`wv'xt==1
label variable raddurd "raddurd: r days final illness/death"

***Whether married or partnered at death***
*wave 2 respondent whether married or partnered at death
gen radmarrp = .
missing exb011 if inw`wv'xt==1, result(radmarrp)
replace radmarrp = 0 if inrange(exb011,2,5) & inw`wv'xt==1
replace radmarrp = 1 if inlist(exb011,1,6) & inw`wv'xt==1
label variable radmarrp "radmarrp: r married/partnered at death"
label values radmarrp yesnomarr

***proxy relationship exit ivw***
*wave 2 respondent proxy relationship  
gen raxprxy = .
missing va2a110 if inw`wv'xt==1, result(raxprxy)
replace raxprxy = 1 if va2a110==3 & inw`wv'xt==1
replace raxprxy = 2 if inlist(va2a110,1,2) & inw`wv'xt==1
replace raxprxy = 3 if inlist(va2a110,4,5) & inw`wv'xt==1
replace raxprxy = 4 if va2a110==6 & inw`wv'xt==1
label variable raxprxy "raxprxy: proxy relationship to r: exit ivw"
label values raxprxy relate

****Grouped Disease that caused death***
**wave 2 respondent grouped disease that caused death

egen temp = group(vas42) if inw`wv'xt==1
replace temp = . if mi(vas42)

**
gen racod_c = .
replace racod_c = .d if inlist(temp,5)
replace racod_c = .m if temp==253
replace racod_c =.m if mi(temp) & inw`wv'xt==1 
replace racod_c = 1 if inlist(temp,3,22,83,89,90,112,152,155,175,180,230)
replace racod_c = 2 if inlist(temp,9,15,21,30,34,35,38,39,85,86,116,117,118,121,123,128,129, ///
																	 130,131,132,133,135,136,149,150,156,157,161,163,164,177,178,179, ///
																	 185,190,191,192,193,195,197,212,213,229,244,245,246,248)
replace racod_c = 3 if inrange(temp,143,148)
replace racod_c = 4 if inlist(temp,2,7,8,12,13,16,40,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79, ///
																	 80,82,84,93,139,140,153,167,168,198,199,200,201,202,204,205,206,207,208,209, ///
																	 210,211,218,222,231,233,242,249,250,251,252)
replace racod_c = 5 if inlist(temp,25,26,28,29,31,42,103,141,169,170,171,172,174,176,181,182,183,184)
replace racod_c = 6 if inlist(temp,23,91,124,154,158,159,160,162,165,166,186,187,188,189,194,196)
replace racod_c = 7 if inlist(temp,44,45)
replace racod_c = 8 if inlist(temp,41,46,94,95,106,137,138,203,214,215,216,217,219,241)
replace racod_c = 9 if inlist(temp,10,11,20,36,87,88,96,97,98,99,100,101,102,119,120,151,232,238,239,240,247)
replace racod_c = 10 if inlist(temp,1,4,6,17,18,19,24,27,32,33,37,43,92,104,105,107,108,109,110,111,113,114,115, ///
																		122,125,126,127,142,220,223,224,225,226,227,228,234,235,236,237,243) | inrange(temp,47,61)
replace racod_c = 11 if inlist(temp,14,81,134,173,221)
label variable racod_c "racod_c: disease that caused r's death"
label values racod_c causes

**
gen ragcod = .
replace ragcod = .d if racod_c == .d & inw`wv'xt==1
replace ragcod = .m if racod_c == .m & inw`wv'xt==1
replace ragcod = 1 if inlist(racod_c,2) & inw`wv'xt==1
replace ragcod = 2 if inlist(racod_c,4) & inw`wv'xt==1
replace ragcod = 3 if inlist(racod_c,1,3,5,6,7,8,9,10,11) & inw`wv'xt==1
label variable ragcod "ragcod: grouped disease that caused r's death"
label values ragcod grpcaus

drop temp


***drop Harmonized CHARLS wave 2 variables***
drop `demogxt_w2_hcharls'

***drop CHARLS EOL Weights variables***
drop `demogxt_w2_wt'

****drop CHARLS EOL Exit Interview variables***
drop `demogxt_w2_xt'

****drop CHARLS EOL Verbal Autopsy variables***
drop `demogxt_w2_va'


******************************************************************************************



***CURRENT WAVE (to be modified at each new wave)***
local wv=2

***In exit interview***
gen inxt = .
replace inxt = 0 if inw2xt==0 
replace inxt = 1 if inw2xt==1 
label variable inxt "inxt: r in exit interview"
label values inxt inwxt

***Exit Interview Wave***
gen raxt = .
forvalues w = 2 / `wv' {
	replace raxt = `w' if inw`w'xt==1
}
label variable raxt "raxt: r exit interview wave"





******************************************************************************************




*gender
tab ragender if in_charls == 1, m

*age catagories
sum radage, d

egen radagecat_i  = cut(radage), at(20,70,80,90,199) icode
tab radagecat_i,m



******************************************************************************************

label define yesnoposs ///
	0 "0.no" ///
	1 "1.yes" ///
	2 "2.possible" ///
	.q ".q:not asked this wave"

label define dispute ///
	0 "0.no dispute" ///
	1 "1.disp prv wv"
	
***yes or no***
label define yesnoh ///
	0 "0.no" ///
	1 "1.yes" ///
	.n ".n:not applicable" ///
	.w ".w:no will" ///
	.t ".t:disputes record" ///
	.u ".u:unmarried/unpartnered" ///
	.i ".i:records inaccurate" ///
	.q ".q:not asked this wave" ///
	.x ".x:not applicable" ///
	.f ".f:funeral expenses" ///
	.e ".e:estate" ///
	.o ".o:other" ///
	.c ".c:not a health condition" ///
	.a ".a:younger than 65" ///
	.s ".s:skipped"

*set wave number
local wv=2
local pre_wv=1



****merge with wave 2 harmonized CHARLS data***
local healthxt_w2_hcharls r1cancre r1lunge r1hearte r1stroke r1diabe r1hibpe
merge 1:1 ID using "$h_charls", keepusing(`healthxt_w2_hcharls') nogen

*****merge with wave 2 CHARLS Exit Interview***
local healthxt_w2_xt exda007_w2_1_4_ exda007_w2_2_4_ exda007_w2_1_5_ exda007_w2_2_5_ exda007_w2_1_7_ exda007_w2_2_7_ ///
										 exda007_w2_1_8_ exda007_w2_2_8_ exda019_w2_1 exda007_w2_5 exda007_w2_7
merge 1:1 ID using "$wave_2_xt", keepusing(`healthxt_w2_xt')

drop if _merge==2
drop _merge

*****merge with wave 2 CHARLS Verbal Autopsy***
local healthxt_w2_va va3a180 va3a210 va3a150 va3a170 va3a220 va3b420
merge 1:1 ID using "$wave_2_va", keepusing(`healthxt_w2_va') 

drop if _merge==2
drop _merge



**********************************************************************************

***ever had cancer last ivw***
*wave 2 ever had cancer last ivw
gen ralcancre = .
replace ralcancre = r1cancre if ralstcore==1 & inw`wv'xt==1
label variable ralcancre "ralcancre: r ever had cancer as of last ivw"
label values ralcancre yesnoh

***ever had lung disease last ivw***
*wave 2 ever had lung disease last ivw
gen rallunge = .
replace rallunge = r1lunge if ralstcore==1 & inw`wv'xt==1
label variable rallunge "rallunge: r ever had lung disease as of last ivw"
label values rallunge yesnoh

***ever had heart problems last ivw***
*wave 2 ever had heart problems last ivw
gen ralhearte = .
replace ralhearte = r1hearte if ralstcore==1 & inw`wv'xt==1
label variable ralhearte "ralhearte: r ever had heart problems as of last ivw"
label values ralhearte yesnoh

***ever had stroke last ivw***
*wave 2 ever had stroke last ivw
gen ralstroke = .
replace ralstroke = r1stroke if ralstcore==1 & inw`wv'xt==1
label variable ralstroke "ralstroke: r ever had stroke as of last ivw"
label values ralstroke yesnoh

***ever had diabetes last ivw***
*wave 2 ever had diabetes last ivw
gen raldiabe = .
replace raldiabe = r1diabe if ralstcore==1 & inw`wv'xt==1
label variable raldiabe "raldiabe: r ever had diabetes as of last ivw"
label values raldiabe yesnoh

***ever had high blood pressure last inw***
*wave 2 ever had high blood pressure
gen ralhibpe = .
replace ralhibpe = r1hibpe if ralstcore==1 & inw`wv'xt==1
label variable ralhibpe "ralhibpe: r ever had high blood pressure as of last ivw"
label values ralhibpe yesnoh

****************************

***ever had cancer***
*wave 2 respondent ever had cancer 
gen raxcancre = .
missing ralcancre exda007_w2_2_4_ if inw`wv'xt==1, result(raxcancre) wave(`wv')
replace raxcancre = 0 if ralcancre==0 & inw`wv'xt==1
replace raxcancre = 0 if exda007_w2_2_4_==2 & inw`wv'xt==1
replace raxcancre = 1 if ralcancre==1 & inw`wv'xt==1
replace raxcancre = 1 if ralcancre==0 & exda007_w2_1_4_==2
replace raxcancre = 1 if exda007_w2_2_4_==1 & inw`wv'xt==1
label variable raxcancre "raxcancre: r ever had cancer in lifetime"
label values raxcancre yesnoh

***cancer flag***
*wave 2 respondent cancer flag
gen raxcancrf = .
missing exda007_w2_1_4_ if inw`wv'xt==1, result(raxcancrf) wave(`wv')
replace raxcancrf = 0 if exda007_w2_1_4_==1 & inw`wv'xt==1
replace raxcancrf = 1 if exda007_w2_1_4_==2 & inw`wv'xt==1
label variable raxcancrf "raxcancrf: r dispute flag previous cancer"
label values raxcancrf dispute

***cancer since last ivw***
*wave 2 respondent cancer since last ivw
gen raxcancr = .
missing exda007_w2_2_4_ if inw`wv'xt==1, result(raxcancr) wave(`wv')
replace raxcancr = 0 if (ralcancre==1 & exda007_w2_1_4_==1) | (ralcancre==0 & exda007_w2_1_4_==2)
replace raxcancr = 0 if exda007_w2_2_4_==2 & inw`wv'xt==1
replace raxcancr = 1 if exda007_w2_2_4_==1 & inw`wv'xt==1
label variable raxcancr "raxcancr: r new report of cancer since last ivw"
label values raxcancr yesnoh




***ever had chronic lung disease***      
*wave 2 respondent ever had chronic lung disease 
gen raxlunge = .
missing rallunge exda007_w2_2_5_ va3a210 if inw`wv'xt==1, result(raxlunge) wave(`wv') 
replace raxlunge = .d if va3a210==3 & inw`wv'xt==1
replace raxlunge = 0 if rallunge==0 & inw`wv'xt==1
replace raxlunge = 0 if (exda007_w2_2_5_==2 | va3a210==2) & inw`wv'xt==1
replace raxlunge = 1 if rallunge==1 & inw`wv'xt==1
replace raxlunge = 1 if rallunge==0 & exda007_w2_1_5_==2
replace raxlunge = 1 if exda007_w2_2_5_==1 & inw`wv'xt==1
replace raxlunge = 1 if va3a210==1 & inw`wv'xt==1
label variable raxlunge "raxlunge: r ever had chronic lung disease in lifetime"
label values raxlunge yesnoh

***chronic lung disease flag***
*wave 2 respondent chronic lung disease flag
gen raxlungf = .
missing exda007_w2_1_5_ if inw`wv'xt==1, result(raxlungf) wave(`wv')
replace raxlungf = 0 if exda007_w2_1_5_==1 & inw`wv'xt==1
replace raxlungf = 1 if exda007_w2_1_5_==2 & inw`wv'xt==1
label variable raxlungf "raxlungf: r dispute flag previous chronic lung disease"
label values raxlungf dispute

***chronic lung disease since last ivw***
*wave 2 respondent chronic lung disease since last ivw
gen raxlung = .
missing exda007_w2_2_5_ if inw`wv'xt==1, result(raxlung) wave(`wv')
replace raxlung = 0 if (rallunge==1 & exda007_w2_1_5_==1) | (rallunge==0 & exda007_w2_1_5_==2)
replace raxlung = 0 if exda007_w2_2_5_==2 & inw`wv'xt==1
replace raxlung = 1 if exda007_w2_2_5_==1 & inw`wv'xt==1
label variable raxlung "raxlung: r new report of chronic lung disease since last ivw"
label values raxlung yesnoh




***ever had heart problems***            
*wave 2 respondent ever had heart problems 
gen raxhearte = .
missing ralhearte exda007_w2_2_7_ if inw`wv'xt==1, result(raxhearte) wave(`wv')
replace raxhearte = 0 if ralhearte==0 & inw`wv'xt==1
replace raxhearte = 0 if exda007_w2_2_7_==2 & inw`wv'xt==1
replace raxhearte = 1 if ralhearte==1 & inw`wv'xt==1
replace raxhearte = 1 if ralhearte==0 & exda007_w2_1_7_==2
replace raxhearte = 1 if exda007_w2_2_7_==1 & inw`wv'xt==1
label variable raxhearte "raxhearte: r ever had heart problems in lifetime"
label values raxhearte yesnoh

***heart problems flag***
*wave 2 respondent heart problems flag
gen raxheartf = .
missing exda007_w2_1_7_ if inw`wv'xt==1, result(raxheartf) wave(`wv')
replace raxheartf = 0 if exda007_w2_1_7_==1 & inw`wv'xt==1
replace raxheartf = 1 if exda007_w2_1_7_==2 & inw`wv'xt==1
label variable raxheartf "raxheartf: r dispute flag previous heart problems"
label values raxheartf dispute

***heart problems since last ivw***
*wave 2 respondent heart problems since last ivw
gen raxheart = .
missing exda007_w2_2_7_ if inw`wv'xt==1, result(raxheart) wave(`wv')
replace raxheart = 0 if (ralhearte==1 & exda007_w2_1_7_==1) | (ralhearte==0 & exda007_w2_1_7_==2)
replace raxheart = 0 if exda007_w2_2_7_==2 & inw`wv'xt==1
replace raxheart = 1 if exda007_w2_2_7_==1 & inw`wv'xt==1
label variable raxheart "raxheart: r new report of heart problems since last ivw"
label values raxheart yesnoh


***heart attack since last ivw***
*wave 2 respondent heart attack since last ivw
gen raxhrtatt = .
missing exda007_w2_5 ralhearte if inw`wv'xt==1, result(raxhrtatt) wave(`wv')
replace raxhrtatt = 0 if (ralhearte==0 & exda007_w2_1_7_==1 & exda007_w2_2_7_==2) | ///
												 (ralhearte==1 & exda007_w2_1_7_==2 & exda007_w2_2_7_==2)
replace raxhrtatt = 0 if exda007_w2_5==2 & inw`wv'xt==1
replace raxhrtatt = 1 if exda007_w2_5==1 & inw`wv'xt==1
label variable raxhrtatt "raxhrtatt: r new report of heart attack since last ivw"
label values raxhrtatt yesnoh




***ever had stroke***            
*wave 2 respondent ever had stroke 
gen raxstroke = .
missing ralstroke exda007_w2_2_8_ if inw`wv'xt==1, result(raxstroke) wave(`wv')
replace raxstroke = 0 if ralstroke==0 & inw`wv'xt==1
replace raxstroke = 0 if exda007_w2_2_8_==2 & inw`wv'xt==1
replace raxstroke = 1 if ralstroke==1 & inw`wv'xt==1
replace raxstroke = 1 if ralstroke==0 & exda007_w2_1_8_==2
replace raxstroke = 1 if exda007_w2_2_8_==1 & inw`wv'xt==1
label variable raxstroke "raxstroke: r ever had stroke in lifetime"
label values raxstroke yesnoh

***stroke flag***
*wave 2 respondent stroke flag
gen raxstrokf = .
missing exda007_w2_1_8_ if inw`wv'xt==1, result(raxstrokf) wave(`wv')
replace raxstrokf = 0 if exda007_w2_1_8_==1 & inw`wv'xt==1
replace raxstrokf = 1 if exda007_w2_1_8_==2 & inw`wv'xt==1
label variable raxstrokf "raxstrokf: r dispute flag previous stroke"
label values raxstrokf dispute

***stroke since last ivw***
*wave 2 respondent stroke since last ivw
gen raxstrok = .
missing exda007_w2_2_8_ exda019_w2_1 if inw`wv'xt==1, result(raxstrok) wave(`wv')
replace raxstrok = 0 if (ralstroke==1 & exda007_w2_1_8_==1) | (ralstroke==0 & exda007_w2_1_8_==2)
replace raxstrok = 0 if (exda007_w2_2_8_==2 | exda019_w2_1==2) & inw`wv'xt==1
replace raxstrok = 1 if exda007_w2_2_8_==1 & inw`wv'xt==1
replace raxstrok = 1 if exda019_w2_1==1 & inw`wv'xt==1
label variable raxstrok "raxstrok: r new report of stroke since last ivw"
label values raxstrok yesnoh


***had memory problems one month before death***
*wave 2 respondent had memory problems one month before death
gen raxmemry1m = .
missing raxmemry1m exda007_w2_7 if inw`wv'xt==1, result(raxmemry1m) wave(`wv')
replace raxmemry1m = 0 if exda007_w2_7==2 & inw`wv'xt==1
replace raxmemry1m = 1 if exda007_w2_7==1 & inw`wv'xt==1
label variable raxmemry1m "raxmemry1m: r had memory problems one month before death"
label values raxmemry1m yesnoh


***ever had memory problems
gen raxmemrye = .
missing va3a220 va3b420 if inw`wv'xt==1, result(raxmemrye) wave(`wv')
replace raxmemrye = .d if (va3a220==3 | va3b420==3) & inw`wv'xt==1
replace raxmemrye = 0 if (va3a220==2 | va3b420==2) & inw`wv'xt==1
replace raxmemrye = 1 if (va3a220==1 | va3b420==1) & inw`wv'xt==1
label variable raxmemrye "raxmemrye: r ever had memory problems in lifetime"
label values raxmemrye yesnoh


***ever had high blood pressure***            
*wave 2 respondent ever had high blood pressure
gen raxhibpe = .
missing ralhibpe va3a150 if inw`wv'xt==1, result(raxhibpe) wave(`wv')
replace raxhibpe = .d if va3a150==3 & inw`wv'xt==1
replace raxhibpe = 0 if ralhibpe==0 & inw`wv'xt==1
replace raxhibpe = 0 if va3a150==2 & inw`wv'xt==1
replace raxhibpe = 1 if ralhibpe==1 & inw`wv'xt==1
replace raxhibpe = 1 if va3a150==1 & inw`wv'xt==1
label variable raxhibpe "raxhibpe: r ever had high blood pressure in lifetime"
label values raxhibpe yesnoh


***ever had high diabetes***            
*wave 2 respondent ever had diabetes
gen raxdiabe = .
missing raldiabe va3a170 if inw`wv'xt==1, result(raxdiabe) wave(`wv')
replace raxdiabe = .d if va3a170==3 & inw`wv'xt==1
replace raxdiabe = 0 if raldiabe==0 & inw`wv'xt==1
replace raxdiabe = 0 if va3a170==2 & inw`wv'xt==1
replace raxdiabe = 1 if raldiabe==1 & inw`wv'xt==1
replace raxdiabe = 1 if va3a170==1 & inw`wv'xt==1
label variable raxdiabe "raxdiabe: r ever had diabetes in lifetime"
label values raxdiabe yesnoh


**********************************************************************************

***drop Harmonized CHARLS wave 2 variables***
drop `healthxt_w2_hcharls'

****drop CHARLS EOL Exit Interview variables***
drop `healthxt_w2_xt'

****drop CHARLS EOL Verbal Autopsy variables***
drop `healthxt_w2_va'


******************************************************************************************



	
***yes/no insurance***
label define yesnoins ///
	0 "0.no" ///
	1 "1.yes" ///
	.x ".x:no hospital stay" ///
	.o ".o:other insurance"

***yes/no dental**
label define yesnodent ///
	0 "0.no" ///
	1 "1.yes" ///
	.x ".x:no dental visits" 
	
***govt ins type***
label define govtype ///
	1 "1.National Health Insurance" ///
	2 "2.Medical Aid Program" ///
	.n ".n:not eligible"
	
***grouped length hospital stay***	
label define hospitalstay ///
	0 "0.0 nights" ///
	1 "1.less than 1 week" ///
	2 "2.1 week to lt 1 month" ///
	3 "3.1 month to lt 3 months" ///
	4 "4.3 months to lt 6 months" ///
	5 "5.6 months to lt 1 year" ///
	6 "6.1 year or more" ///
	.x ".x:did not die in hospital" 
	
***grouped length nursing home stay***	
label define nhstay ///
	0 "0.0 nights" ///
	1 "1.less than 1 week" ///
	2 "2.1 week to lt 1 month" ///
	3 "3.1 month to lt 3 months" ///
	4 "4.3 months to lt 6 months" ///
	5 "5.6 months to lt 1 year" ///
	6 "6.1 year or more" ///
	.x ".x:did not die in nursing home" 
	
***grouped length hospice stay***	
label define hospicestay ///
	0 "0.0 nights" ///
	1 "1.less than 1 week" ///
	2 "2.1 week to lt 1 month" ///
	3 "3.1 month to lt 3 months" ///
	4 "4.3 months to lt 6 months" ///
	5 "5.6 months to lt 1 year" ///
	6 "6.1 year or more" ///
	.x ".x:did not die in hospice" 
	
***grouped length hospital, hospice, nh stays***
label define hhnhstays ///
	0 "0.0 nights" ///
	1 "1.less than 1 week" ///
	2 "2.1 week to lt 1 month" ///
	3 "3.1 month to lt 3 months" ///
	4 "4.3 months to lt 6 months" ///
	5 "5.6 months to lt 1 year" ///
	6 "6.1 year or more" 
	
***imputation flag insurance***
label define flagins ///
  -1 "-1.not imputed, missing neighbors" ///
  -2 "-2.not imputed, missing covariates" ///
	1 "1.continuous value" ///
	2 "2.closed bracket" ///
	3 "3.open bracket" ///
	5 "5.no bracket info" ///
	6 "6.no expense" ///
	7 "7.dk had expense" ///
	.x ".x:not asked, less than 10k total" ///
	.h ".h:no help" ///
	.q ".q:not asked this wave" 

***who helped pay***
label define whocost ///
	1 "1.child" /// 
	2 "2.relative" ///
	3 "3.other" ///
	4 "4.child and relative" ///
	5 "5.child and other" ///
	.h ".h:no help" 

	
	

*set wave number
local wv=2
local pre_wv=1




*****merge with wave 2 CHARLS Exit Interview***
local insxt_w2_xt exea001s? exea001s1? exed030_w2 exed031_w2 exed031_w2_1 exed032_w2 exed032_w2_1 exeg000_w2 /// 
									exeg001_w2_1 exeg001_w2_2 exeg001_w2_3 exeg001_w2_4 exeg001_w2_5 /// 
									exeg003_w2 exeg004_w2 exeg005_w2 exeg006_w2 exeg007_w2 exeg008_w2 exeg009_w2 ///
									exeg010_w2 exeg010_w2_1 exeg011_w2 exeg011_w2_1 exef001s? exeh001 exeh002 ///
									exef001s? exef002_2_ exef002_1_2_ exef003_2_ exef003_1_2_ ///
									exef002_1_ exef002_1_1_ exef003_1_ exef003_1_1_ exef002_3_ exef002_1_3_ exef003_3_ exef003_1_3_ ///
									exef002_4_ exef002_1_4_ exef003_4_ exef003_1_4_ exef002_5_ exef002_1_5_ exef003_5_ exef003_1_5_ ///
									exeh003 exeh003_1 exeh004 exeh004_1
merge 1:1 ID using "$wave_2_xt", keepusing(`insxt_w2_xt')

drop if _merge==2
drop _merge

**********************************************************************************

***Government health insurance***  
*wave 2 respondent
gen raxhigov = .
missing exea001s1 exea001s2 exea001s3 exea001s4 exea001s5 exea001s6 exea001s7 exea001s8 exea001s9 exea001s10 exea001s11 if inw`wv'xt==1, result(raxhigov)
replace raxhigov = .o if exea001s10==10
replace raxhigov = 0 if (exea001s7==7 | exea001s8==8 | exea001s11==11) & inw`wv'xt==1
replace raxhigov = 1 if exea001s1==1
replace raxhigov = 1 if exea001s2==2
replace raxhigov = 1 if exea001s3==3
replace raxhigov = 1 if exea001s4==4
replace raxhigov = 1 if exea001s5==5
replace raxhigov = 1 if exea001s6==6
replace raxhigov = 1 if exea001s9==9
label variable raxhigov "raxhigov:r covered by gov health insurance plan"
label values raxhigov yesnoins

***Private health insurance***  
*wave 2 respondent
gen raxhipriv = .
missing exea001s1 exea001s2 exea001s3 exea001s4 exea001s5 exea001s6 exea001s7 exea001s8 exea001s9 exea001s10 exea001s11 if inw`wv'xt==1, result(raxhipriv)
replace raxhipriv = .o if exea001s10==10
replace raxhipriv = 0 if (exea001s1==1 | exea001s2==2 | exea001s3==3 | exea001s4==4 | exea001s5==5 | exea001s6==6 | exea001s9==9 | exea001s11==11) & inw`wv'xt==1
replace raxhipriv = 1 if exea001s7==7
replace raxhipriv = 1 if exea001s8==8
label variable raxhipriv "raxhipriv:r covered by private health insurance plan"
label values raxhipriv yesnoins



***Any health visit one month before death***
gen raxdoctor1m = .
missing exed030_w2 if inw`wv'xt==1, result(raxdoctor1m)
replace raxdoctor1m = 0 if exed030_w2==0
replace raxdoctor1m = 1 if inrange(exed030_w2,1,1000)
label variable raxdoctor1m "raxdoctor1m: r any health visits one month before death"
label values raxdoctor1m yesnoins

***Number of health visits one month before death***
gen raxdoctim1m = .
missing exed030_w2 if inw`wv'xt==1, result(raxdoctim1m)
replace raxdoctim1m = 0 if raxdoctor1m==0
replace raxdoctim1m = exed030_w2 if !mi(exed030_w2) & raxdoctor1m==1
label variable raxdoctim1m "raxdoctim1m: r # health visits one month before death"



***Number of nights final hospital stay before death***
gen radhospnit = .
destring exeg001_w2_1 exeg001_w2_2 exeg001_w2_3 exeg001_w2_4 exeg001_w2_5, replace
missing exeg001_w2_1 exeg001_w2_2 exeg001_w2_3 exeg001_w2_4 exeg001_w2_5 if inw`wv'xt==1, result(radhospnit)
replace radhospnit = .x if exeg000_w2==2
replace radhospnit = 1 if inrange(exeg001_w2_1,1,24)
replace radhospnit = exeg001_w2_2 if inrange(exeg001_w2_2,1,365)
replace radhospnit = (exeg001_w2_3)*7 if inrange(exeg001_w2_3,0.1,3.9)
replace radhospnit = (exeg001_w2_4)*30.4 if inrange(exeg001_w2_4,0.1,12)
replace radhospnit = (exeg001_w2_5)*365 if inrange(exeg001_w2_5,0.1,10)
label variable radhospnit "radhospnit: r # nights final hospital stay before death"

***Categorical duration final hospital stay before death***
gen radhospnitd = .
replace radhospnitd = .m if radhospnit==.m
replace radhospnitd = .d if radhospnit==.d
replace radhospnitd = .r if radhospnit==.r
replace radhospnitd = .x if radhospnit==.x
replace radhospnitd = 0 if radhospnit==0
replace radhospnitd = 1 if inrange(exeg001_w2_1,1,24) | ///
													 inrange(exeg001_w2_2,1,6)
replace radhospnitd = 2 if inrange(exeg001_w2_2,7,30) | ///
													 inrange(exeg001_w2_3,1,3) | ///
													 exeg001_w2_4==.5
replace radhospnitd = 3 if inrange(exeg001_w2_2,31,91) | ///
													 inrange(exeg001_w2_4,1,2)
replace radhospnitd = 4 if inrange(exeg001_w2_4,3,5)
replace radhospnitd = 5 if inrange(exeg001_w2_4,6,11)
replace radhospnitd = 6 if inrange(exeg001_w2_5,1,2)
label variable radhospnitd "radhospnitd: r duration final hospital stay before death"
label values radhospnitd hospitalstay

***Any hospital stay one year before death (apart from the one mentioned in radhospnit)***
gen raxhosp1y = .
missing exeg004_w2 if inw`wv'xt==1, result(raxhosp1y)
replace raxhosp1y = 0 if exeg004_w2==2
replace raxhosp1y = 1 if exeg004_w2==1
label variable raxhosp1y "raxhosp1y: r any hospital stay during one year before death"
label values raxhosp1y yesnoins

***Number of hospital stays one year before death***
gen raxhsptim1y = .
missing exeg005_w2 exeg004_w2 if inw`wv'xt==1, result(raxhsptim1y)
replace raxhsptim1y = 0 if exeg004_w2==2
replace raxhsptim1y = exeg005_w2 if !mi(exeg005_w2)
label variable raxhsptim1y "raxhsptim1y: r # hospital stays during one year before death"

***Any hospital ICU stay during any hospital visit***
gen raxhspicu = .
missing exeg006_w2 if inw`wv'xt==1, result(raxhspicu)
replace raxhspicu = .x if raxhsptim1y==0 & inw`wv'xt==1 
replace raxhspicu = 0 if exeg006_w2==2
replace raxhspicu = 1 if exeg006_w2==1
label variable raxhspicu "raxhspicu: r in icu during hospital stay"
label values raxhspicu yesnoins

***Any life support equipment during any hospital visit***
gen raxhsplfs = .
missing exeg007_w2 if inw`wv'xt==1, result(raxhsplfs)
replace raxhsplfs = .x if raxhsptim1y==0 & inw`wv'xt==1 
replace raxhsplfs = 0 if exeg007_w2==2
replace raxhsplfs = 1 if exeg007_w2==1
label variable raxhsplfs "raxhsplfs: r on life support during hospital stay"
label values raxhsplfs yesnoins

***Any kidney dialisis services during any hospital visit***
gen raxhspkds = .
missing exeg008_w2 if inw`wv'xt==1, result(raxhspkds)
replace raxhspkds = .x if raxhsptim1y==0 & inw`wv'xt==1 
replace raxhspkds = 0 if exeg008_w2==2
replace raxhspkds = 1 if exeg008_w2==1
label variable raxhspkds "raxhspkds: r received kidney dialysis during hospital stay"
label values raxhspkds yesnoins

***Any antibiotics during any hospital visit***
gen raxhspanb = .
missing exeg009_w2 if inw`wv'xt==1, result(raxhspanb)
replace raxhspanb = .x if raxhsptim1y==0 & inw`wv'xt==1 
replace raxhspanb = 0 if exeg009_w2==2
replace raxhspanb = 1 if exeg009_w2==1
label variable raxhspanb "raxhspanb: r received antibiotics during hospital stay"
label values raxhspanb yesnoins


***Any prescription drug during last year of life***
gen raxdrugs = .
missing exef001s1 exef001s2 exef001s3 exef001s4 exef001s5 exef001s6 exef001s7 if inw`wv'xt==1, result(raxdrugs)
replace raxdrugs = 0 if (exef001s1==1 | exef001s3==3 | exef001s4==4 | exef001s5==5 | exef001s6==6 | exef001s7==7)
replace raxdrugs = 1 if exef001s2==2
label variable raxdrugs "raxdrugs: r took prescription drugs one year before death"
label values raxdrugs yesnoins


***Any dentist visit during last year of life***
gen raxdentst1y = .
missing exeh001 if inw`wv'xt==1, result(raxdentst1y)
replace raxdentst1y = 0 if exeh001==2
replace raxdentst1y = 1 if exeh001==1
label variable raxdentst1y "raxdentst1y: r any dentist visits one year before death"
label values raxdentst1y yesnoins

***Number of times received dental care during last year of life***
gen raxdentim1y = .
missing exeh001 exeh002 if inw`wv'xt==1, result(raxdentim1y)
replace raxdentim1y = 0 if exeh001==2
replace raxdentim1y = exeh002 if !mi(exeh002) & exeh001==1
label variable raxdentim1y "raxdentim1y: # dental care visits one year before death"



***Cost variables, imputation***

*********MONTHLY VALUES*********
***Total cost of health visits one month before death***
gen raxtotdoc1m = .
label variable raxtotdoc1m "raxtotdoc1m: r total cost: health visits one month before death"

gen raxtotdocf1m = .
label variable raxtotdocf1m "raxtotdocf1m: r total cost flag: health visits one month before death"
label values raxtotdocf1m flagins

gen tdoc_o = .
replace tdoc_o = 0 if (raxdoctor1m==0 & inw`wv'xt==1) | exed031_w2==2
replace tdoc_o = 1 if raxdoctor1m==1 & inw`wv'xt==1 

gen tdoc_ = .
replace tdoc_ = exed031_w2_1 if inrange(exed031_w2_1,0,500000)

gen tdoc_min = .
gen tdoc_max = .

***Out-of-pocket cost of health visits one month before death***
gen raxoopdoc1m = .
label variable raxoopdoc1m "raxoopdoc1m: r OOP cost: health visits one month before death"

gen raxoopdocf1m = .
label variable raxoopdocf1m "raxoopdocf1m: r OOP cost flag: health visits one month before death"
label values raxoopdocf1m flagins

gen doc_o = .
replace doc_o = 0 if (raxdoctor1m==0 & inw`wv'xt==1) | exed031_w2==2 | exed032_w2==2 
replace doc_o = 1 if raxdoctor1m==1 & inw`wv'xt==1 

gen doc_ = .
replace doc_ = exed032_w2_1 if inrange(exed032_w2_1,0,200000)

gen doc_min = .
gen doc_max = .





*********YEARLY VALUES*********

***Total cost for hospital bills in the one year before death*** 
gen raxtothos1y = .
label variable raxtothos1y "raxtothos1y: r total cost: hospital one year before death"

gen raxtothosf1y = .
label variable raxtothosf1y "raxtothosf1y: r total cost flag: hospital one year before death"
label values raxtothosf1y flagins

gen thos_o = .
replace thos_o = 0 if (raxhosp1y==0 & inw`wv'xt==1) | exeg010_w2==2
replace thos_o = 1 if raxhosp1y==1 & inw`wv'xt==1 

gen thos_ = .
replace thos_ = exeg010_w2_1 if inrange(exeg010_w2_1,0,400000)

gen thos_min = .
gen thos_max = .

***Out of pocket cost for hospital bills in the one year before death***  
gen raxoophos1y = .
label variable raxoophos1y "raxoophos1y: r OOP cost: hospital one year before death"

gen raxoophosf1y = .
label variable raxoophosf1y "raxoophosf1y: r OOP cost flag: hospital one year before death"
label values raxoophosf1y flagins

gen hos_o = .
replace hos_o = 0 if (raxhosp1y==0 & inw`wv'xt==1) | exeg010_w2==2 | exeg011_w2==2
replace hos_o = 1 if raxhosp1y==1 & inw`wv'xt==1

gen hos_ = .
replace hos_ = exeg011_w2_1 if inrange(exeg011_w2_1,0,400000) //1 obs at 50,000 total and 200,000 oop

gen hos_min = .
gen hos_max = .


***Total cost for prescription drugs in the one year before death*** (Just include prescription drugs: exef002_2_ exef002_1_2_)
gen raxtotdrug1y = .
label variable raxtotdrug1y "raxtotdrug1y: r total cost: prescription drugs one year before death"

gen raxtotdrugf1y = .
label variable raxtotdrugf1y "raxtotdrugf1y: r total cost flag: prescription drugs one year before death"
label values raxtotdrugf1y flagins

gen tdrug_o = .
replace tdrug_o = 0 if (raxdrugs==0 & inw`wv'xt==1) | exef002_2_==2
replace tdrug_o = 1 if raxdrugs==1 & inw`wv'xt==1 

gen tdrug_ = .
replace tdrug_ = exef002_1_2_ if inrange(exef002_1_2_,0,110000)

gen tdrug_min = .
gen tdrug_max = .


***Out of pocket cost for prescription drugs in the one year before death***  
gen raxoopdrug1y = .
label variable raxoopdrug1y "raxoopdrug1y: r OOP cost: prescription drugs one year before death"

gen raxoopdrugf1y = .
label variable raxoopdrugf1y "raxoopdrugf1y: r OOP cost flag: prescription drugs one year before death"
label values raxoopdrugf1y flagins

gen drug_o = .
replace drug_o = 0 if (raxdrugs==0 & inw`wv'xt==1) | exef002_2_==2 | exef003_2_==2
replace drug_o = 1 if raxdrugs==1 & inw`wv'xt==1 

gen drug_ = .
replace drug_ = exef003_1_2_ if inrange(exef003_1_2_,0,200000) //1 obs at 5,000 total and 200,000 oop

gen drug_min = .
gen drug_max = .



***Total cost for dental care in the one year before death*** 
gen raxtotden1y = .
label variable raxtotden1y "raxtotden1y: r total cost: dental care one year before death"

gen raxtotdenf1y = .
label variable raxtotdenf1y "raxtotdenf1y: r total cost flag: dental care one year before death"
label values raxtotdenf1y flagins

gen tden_o = .
replace tden_o = 0 if (raxdentst1y==0 & inw`wv'xt==1) | exeh003==2
replace tden_o = 1 if raxdentst1y==1 & inw`wv'xt==1 

gen tden_ = .
replace tden_ = exeh003_1 if inrange(exeh003_1,0,8000)

gen tden_min = .
gen tden_max = .


***Out of pocket cost for dental care in the one year before death***  
gen raxoopden1y = .
label variable raxoopden1y "raxoopden1y: r OOP cost: dental care one year before death"

gen raxoopdenf1y = .
label variable raxoopdenf1y "raxoopdenf1y: r OOP cost flag: dental care one year before death"
label values raxoopdenf1y flagins

gen den_o = .
replace den_o = 0 if (raxdentst1y==0 & inw`wv'xt==1) | exeh003==2 | exeh004==2
replace den_o = 1 if raxdentst1y==1 & inw`wv'xt==1 

gen den_ = .
replace den_ = exeh004_1 if inrange(exeh004_1,0,4000)

gen den_min = .
gen den_max = .



********COSTS FOR OTHER MEDICAL EXPENDITURES in exef002/exef003 THAT ARE NOT PRESCRIPTION DRUGS
***Total cost for over-the-counter modern drugs in the one year before death*** (Just include over-the-counter modern drugs: exef002_1_ exef002_1_1_)
gen raxtotdrug_1_1y = .
label variable raxtotdrug_1_1y "raxtotdrug_1_1y: r total cost: over-the-counter modern drugs one year before death"

gen raxtotdrug_1_f1y = .
label variable raxtotdrug_1_f1y "raxtotdrug_1_f1y: r total cost flag: over-the-counter modern drugs one year before death"
label values raxtotdrug_1_f1y flagins

gen tdrug1_o = .
replace tdrug1_o = 0 if (exef001s2==2 | exef001s3==3 | exef001s4==4 | exef001s5==5 | exef001s6==6 | exef001s7==7) | exef002_1_==2
replace tdrug1_o = 1 if exef001s1==1  & inw`wv'xt==1 

gen tdrug1_ = .
replace tdrug1_ = exef002_1_1_ if inrange(exef002_1_1_,0,20000)

gen tdrug1_min = .
gen tdrug1_max = .


***Out of pocket cost for over-the-counter modern drugs in the one year before death***     RE_CODE ALL THE VARIABLES BASED ON THIS ONE
gen raxoopdrug_1_1y = .
label variable raxoopdrug_1_1y "raxoopdrug_1_1y: r OOP cost: over-the-counter modern drugs one year before death"

gen raxoopdrug_1_f1y = .
label variable raxoopdrug_1_f1y "raxoopdrug_1_f1y: r OOP cost flag: over-the-counter modern drugs one year before death"
label values raxoopdrug_1_f1y flagins

gen drug1_o = .
replace drug1_o = 0 if (exef001s2==2 | exef001s3==3 | exef001s4==4 | exef001s5==5 | exef001s6==6 | exef001s7==7) | exef002_1_==2 | exef003_1_==2
replace drug1_o = 1 if exef001s1==1  

gen drug1_ = .
replace drug1_ = exef003_1_1_ if inrange(exef003_1_1_,0,20000) 

gen drug1_min = .
gen drug1_max = .


***Total cost for traditional herbs or traditional medicines in the one year before death*** (Just include traditional herbs or traditional medicines: exef002_3_ exef002_1_3_)
gen raxtotdrug_3_1y = .
label variable raxtotdrug_3_1y "raxtotdrug_3_1y: r total cost: traditional herbs or traditional medicines one year before death"

gen raxtotdrug_3_f1y = .
label variable raxtotdrug_3_f1y "raxtotdrug_3_f1y: r total cost flag: traditional herbs or traditional medicines one year before death"
label values raxtotdrug_3_f1y flagins

gen tdrug3_o = .
replace tdrug3_o = 0 if (exef001s1==1 | exef001s2==2 | exef001s4==4 | exef001s5==5 | exef001s6==6 | exef001s7==7) | exef002_3_==2
replace tdrug3_o = 1 if exef001s3==3 

gen tdrug3_ = .
replace tdrug3_ = exef002_1_3_ if inrange(exef002_1_3_,0,6000)

gen tdrug3_min = .
gen tdrug3_max = .


***Out of pocket cost for traditional herbs or traditional medicines in the one year before death***  
gen raxoopdrug_3_1y = .
label variable raxoopdrug_3_1y "raxoopdrug_3_1y: r OOP cost: traditional herbs or traditional medicines one year before death"

gen raxoopdrug_3_f1y = .
label variable raxoopdrug_3_f1y "raxoopdrug_3_f1y: r OOP cost flag: traditional herbs or traditional medicines one year before death"
label values raxoopdrug_3_f1y flagins

gen drug3_o = .
replace drug3_o = 0 if (exef001s1==1 | exef001s2==2 | exef001s4==4 | exef001s5==5 | exef001s6==6 | exef001s7==7) | exef002_3_==2 | exef003_3_==2
replace drug3_o = 1 if exef001s3==3 

gen drug3_ = .
replace drug3_ = exef003_1_3_ if inrange(exef003_1_3_,0,10000) 

gen drug3_min = .
gen drug3_max = .


***Total cost for tonic/health supplements in the one year before death*** (Just include tonic/health supplements: exef002_4_ exef002_1_4_)
gen raxtotdrug_4_1y = .
label variable raxtotdrug_4_1y "raxtotdrug_4_1y: r total cost: tonic/health supplements one year before death"

gen raxtotdrug_4_f1y = .
label variable raxtotdrug_4_f1y "raxtotdrug_4_f1y: r total cost flag: tonic/health supplements one year before death"
label values raxtotdrug_4_f1y flagins

gen tdrug4_o = .
replace tdrug4_o = 0 if (exef001s1==1 | exef001s2==2 | exef001s3==3 | exef001s5==5 | exef001s6==6 | exef001s7==7) | exef002_4_==2
replace tdrug4_o = 1 if exef001s4==4 

gen tdrug4_ = .
replace tdrug4_ = exef002_1_4_ if inrange(exef002_1_4_,0,9000)

gen tdrug4_min = .
gen tdrug4_max = .


***Out of pocket cost for tonic/health supplements in the one year before death***  
gen raxoopdrug_4_1y = .
label variable raxoopdrug_4_1y "raxoopdrug_4_1y: r OOP cost: tonic/health supplements one year before death"

gen raxoopdrug_4_f1y = .
label variable raxoopdrug_4_f1y "raxoopdrug_4_f1y: r OOP cost flag: tonic/health supplements one year before death"
label values raxoopdrug_4_f1y flagins

gen drug4_o = .
replace drug4_o = 0 if (exef001s1==1 | exef001s2==2 | exef001s3==3 | exef001s5==5 | exef001s6==6 | exef001s7==7) | exef002_4_==2 | exef003_4_==2
replace drug4_o = 1 if exef001s4==4 

gen drug4_ = .
replace drug4_ = exef003_1_4_ if inrange(exef003_1_4_,0,9000) 

gen drug4_min = .
gen drug4_max = .


***Total cost for health care equipment in the one year before death*** (Just include health care equipment: exef002_5_ exef002_1_5_)
gen raxtotdrug_5_1y = .
label variable raxtotdrug_5_1y "raxtotdrug_5_1y: r total cost: health care equipment one year before death"

gen raxtotdrug_5_f1y = .
label variable raxtotdrug_5_f1y "raxtotdrug_5_f1y: r total cost flag: health care equipment one year before death"
label values raxtotdrug_5_f1y flagins

gen tdrug5_o = .
replace tdrug5_o = 0 if (exef001s1==1 | exef001s2==2 | exef001s3==3 | exef001s4==4 | exef001s6==6 | exef001s7==7) | exef002_5_==2
replace tdrug5_o = 1 if exef001s5==5

gen tdrug5_ = .
replace tdrug5_ = exef002_1_5_ if inrange(exef002_1_5_,0,1)

gen tdrug5_min = .
gen tdrug5_max = .


***Out of pocket cost for health care equipment in the one year before death***  
gen raxoopdrug_5_1y = .
label variable raxoopdrug_5_1y "raxoopdrug_5_1y: r OOP cost: health care equipment one year before death"

gen raxoopdrug_5_f1y = .
label variable raxoopdrug_5_f1y "raxoopdrug_5_f1y: r OOP cost flag: health care equipment one year before death"
label values raxoopdrug_5_f1y flagins

gen drug5_o = .
replace drug5_o = 0 if (exef001s1==1 | exef001s2==2 | exef001s3==3 | exef001s4==4 | exef001s6==6 | exef001s7==7) | exef002_5_==2 | exef003_5_==2
replace drug5_o = 1 if exef001s5==5 

gen drug5_ = .
replace drug5_ = exef003_1_5_ if inrange(exef003_1_5_,0,1) 

gen drug5_min = .
gen drug5_max = .



***Total Other Medical Expenditure***
***Total Expenditure***   (raxtotdrug_1_1y+raxtotdrug_3_1y+raxtotdrug_4_1y+raxtotdrug_5_1y)
gen raxtotome1y_c = .
label variable raxtotome1y_c "raxtotome1y_c: r total cost: total other medical expenditure 1 year"

gen raxtotomef1y_c = .
label variable raxtotomef1y_c "raxtotomef1y_c: r total cost flag: total other medical expenditure 1 year"
label values raxtotomef1y_c flagins

***Total Out-of-pocket expenditure*** (raxoopdrug_1_1y+raxoopdrug_3_1y+raxoopdrug_4_1y+raxoopdrug_5_1y)
gen raxoopome1y_c = .
label variable raxoopome1y_c "raxoopome1y_c: r OOP cost: total other medical expenditure 1 year"

gen raxoopomef1y_c = .
label variable raxoopomef1y_c "raxoopomef1y_c: r OOP cost flag: total other medical expenditure 1 year"
label values raxoopomef1y_c flagins






*****TOTAL EXPENDITURE*******
***Total Expenditure***   (RAXTOTDOC1Y+RAXTOTHOS1Y+RAXTOTDRUG1Y_C+RAXOOPDEN1Y)
gen raxtotmd1y_c = .
label variable raxtotmd1y_c "raxtotmd1y_c: r total cost: total major medical expenses 1 year"

gen raxtotmdf1y_c = .
label variable raxtotmdf1y_c "raxtotmdf1y_c: r total cost flag: total major medical expenses 1 year"
label values raxtotmdf1y_c flagins

***Total Out-of-pocket expenditure*** (RAXOOPDOC1Y+RAXOOPHOS1Y+RAXOOPDRUG1Y_C+RAXOOPDEN1Y)
gen raxoopmd1y_c = .
label variable raxoopmd1y_c "raxoopmd1y_c: r OOP cost: total major medical expenses 1 year"

gen raxoopmdf1y_c = .
label variable raxoopmdf1y_c "raxoopmdf1y_c: r OOP cost flag: total major medical expenses 1 year"
label values raxoopmdf1y_c flagins


**********************************************************************************

****drop CHARLS EOL Exit Interview variables***
drop `insxt_w2_xt'


******************************************************************************************



**************MAKE SURE IMPUTED TOTAL COSTS ARE GREATER THAN OR EQUAL TO OOP COSTS******************************
********MONTHLY VALUES**********
***total health visits***
*assign minimum values if have oop cost but no total
replace tdoc_min = doc_ if mi(tdoc_min) & mi(tdoc_) & !mi(doc_) & tdoc_o!=0
*adjust for cpi*
forvalues y = 2011/2014 {
	replace tdoc_min = ((tdoc_min*100)/c`y'cpindex) if raxyear==`y' & inrange(tdoc_min,0,400000)
	replace tdoc_max = ((tdoc_max*100)/c`y'cpindex) if raxyear==`y' & inrange(tdoc_max,0,400000)
	replace tdoc_    = ((tdoc_*100)/c`y'cpindex)    if raxyear==`y' & inrange(tdoc_,0,1000000)
}
*impute missing values*
charls_eol_impute tdoc_ if inxt==1, entry_var(tdoc_o)
*assign to variables*
replace raxtotdoc1m = tdoc__i if !mi(tdoc__i) & inxt==1
replace raxtotdoc1m = .m if raxtotdoc1m==. & inxt==1

replace raxtotdocf1m = tdoc__i_f if !mi(tdoc__i_f) & inxt==1

drop tdoc_o tdoc_min tdoc_max tdoc_ tdoc__i tdoc__i_f tdoc__i_neighbor

***oop health visits***
*adjust ownership*
replace doc_o = 1 if raxtotdocf1m==7 & (raxtotdoc1m==0 | inrange(raxtotdoc1m,629,630)) & doc_o==. & ///
										 (inlist(radage,51,53) | (inlist(radage,80,84) & ragender==2)) //fixing 5 cases
*adjust for cpi*
forvalues y = 2011/2014 {
	replace doc_min = ((doc_min*100)/c`y'cpindex) if raxyear==`y' & inrange(doc_min,0,100000)
	replace doc_max = ((doc_max*100)/c`y'cpindex) if raxyear==`y' & inrange(doc_max,0,100000)
	replace doc_    = ((doc_*100)/c`y'cpindex)    if raxyear==`y' & inrange(doc_,0,1000000)
}
*assign maximum values (already cpi-adjusted)*
replace doc_max = raxtotdoc1m if mi(doc_) & !mi(raxtotdoc1m) & doc_o!=0
*impute missing values*
charls_eol_impute doc_ if inxt==1, entry_var(doc_o)
*assign to variables*
replace raxoopdoc1m = doc__i if !mi(doc__i) & inxt==1
replace raxoopdoc1m = .m if raxoopdoc1m==. & inxt==1

replace raxoopdocf1m = doc__i_f if !mi(doc__i_f) & inxt==1
replace raxoopdocf1m = 7 if raxtotdocf1m==7 & (raxtotdoc1m==0 | inrange(raxtotdoc1m,629,630)) & ///
														(inlist(radage,51,53) | (inlist(radage,80,84) & ragender==2)) //fixing 5 cases

drop doc_o doc_min doc_max doc_ doc__i doc__i_f doc__i_neighbor

***Generate converted yearly values for monthly variables

gen raxtotdoc1y = raxtotdoc1m*12 
replace raxtotdoc1y = .m if raxtotdoc1m==.m
label variable raxtotdoc1y "raxtotdoc1y: r total cost: health visits one year before death"
gen raxtotdocf1y = raxtotdocf1m 
label variable raxtotdocf1y "raxtotdocf1y: r total cost flag: health visits one year before death"
gen raxoopdoc1y = raxoopdoc1m*12
replace raxoopdoc1y = .m if raxoopdoc1m==.m
label variable raxoopdoc1y "raxoopdoc1y: r OOP cost: health visits one year before death"
gen raxoopdocf1y = raxoopdocf1m 
label variable raxoopdocf1y "raxoopdocf1y: r OOP cost flag: health visits one year before death"

********YEARLY VALUES**********
***total hospital***
*adjust for cpi*
forvalues y = 2011/2014 {
	replace thos_min = ((thos_min*100)/c`y'cpindex) if raxyear==`y' & inrange(thos_min,0,400000)
	replace thos_max = ((thos_max*100)/c`y'cpindex) if raxyear==`y' & inrange(thos_max,0,400000)
	replace thos_    = ((thos_*100)/c`y'cpindex)    if raxyear==`y' & inrange(thos_,0,1000000)
}
*impute missing values*
charls_eol_impute thos_ if inxt==1, entry_var(thos_o)
*assign to variables*
replace raxtothos1y = thos__i if !mi(thos__i) & inxt==1
replace raxtothos1y = .m if raxtothos1y==. & inxt==1

replace raxtothosf1y = thos__i_f if !mi(thos__i_f) & inxt==1

drop thos_o thos_min thos_max thos_ thos__i thos__i_f thos__i_neighbor

***oop hospital***
*adjust ownership*
replace hos_o = 1 if raxtothosf1y==7 & inrange(raxtothos1y,1108,1109) & hos_o==. //fixing 1 case
*adjust for cpi*
forvalues y = 2011/2014 {
	replace hos_min = ((hos_min*100)/c`y'cpindex) if raxyear==`y' & inrange(hos_min,0,100000)
	replace hos_max = ((hos_max*100)/c`y'cpindex) if raxyear==`y' & inrange(hos_max,0,100000)
	replace hos_    = ((hos_*100)/c`y'cpindex)    if raxyear==`y' & inrange(hos_,0,1000000)
}
*assign maximum values (already cpi-adjusted)*
replace hos_max = raxtothos1y if mi(hos_) & !mi(raxtothos1y) & hos_o!=0
*impute missing values*
charls_eol_impute hos_ if inxt==1, entry_var(hos_o)
*assign to variables*
replace raxoophos1y = hos__i if !mi(hos__i) & inxt==1
replace raxoophos1y = .m if raxoophos1y==. & inxt==1

replace raxoophosf1y = hos__i_f if !mi(hos__i_f) & inxt==1
replace raxoophosf1y = 7 if raxtothosf1y==7 & inrange(raxtothos1y,1108,1109) //fixing 1 case

drop hos_o hos_min hos_max hos_ hos__i hos__i_f hos__i_neighbor



***total prescription drugs***
*adjust for cpi*
forvalues y = 2011/2014 {
	replace tdrug_min = ((tdrug_min*100)/c`y'cpindex) if raxyear==`y' & inrange(tdrug_min,0,400000)
	replace tdrug_max = ((tdrug_max*100)/c`y'cpindex) if raxyear==`y' & inrange(tdrug_max,0,400000)
	replace tdrug_    = ((tdrug_*100)/c`y'cpindex)    if raxyear==`y' & inrange(tdrug_,0,1000000)
}
*impute missing values*
charls_eol_impute tdrug_ if inxt==1, entry_var(tdrug_o)
*assign to variables*
replace raxtotdrug1y = tdrug__i if !mi(tdrug__i) & inxt==1
replace raxtotdrug1y = .m if raxtotdrug1y==. & inxt==1

replace raxtotdrugf1y = tdrug__i_f if !mi(tdrug__i_f) & inxt==1

drop tdrug_o tdrug_min tdrug_max tdrug_ tdrug__i tdrug__i_f tdrug__i_neighbor

***oop prescription drugs***
*adjust for cpi*
forvalues y = 2011/2014 {
	replace drug_min = ((drug_min*100)/c`y'cpindex) if raxyear==`y' & inrange(drug_min,0,100000)
	replace drug_max = ((drug_max*100)/c`y'cpindex) if raxyear==`y' & inrange(drug_max,0,100000)
	replace drug_    = ((drug_*100)/c`y'cpindex)    if raxyear==`y' & inrange(drug_,0,1000000)
}
*assign maximum values (already cpi-adjusted)*
replace drug_max = raxtotdrug1y if mi(drug_) & !mi(raxtotdrug1y) & drug_o!=0
*impute missing values*
charls_eol_impute drug_ if inxt==1, entry_var(drug_o)
*assign to variables*
replace raxoopdrug1y = drug__i if !mi(drug__i) & inxt==1
replace raxoopdrug1y = .m if raxoopdrug1y==. & inxt==1

replace raxoopdrugf1y = drug__i_f if !mi(drug__i_f) & inxt==1

drop drug_o drug_min drug_max drug_ drug__i drug__i_f drug__i_neighbor




***total dental care***
*adjust for cpi*
forvalues y = 2011/2014 {
	replace tden_min = ((tden_min*100)/c`y'cpindex) if raxyear==`y' & inrange(tden_min,0,400000)
	replace tden_max = ((tden_max*100)/c`y'cpindex) if raxyear==`y' & inrange(tden_max,0,400000)
	replace tden_    = ((tden_*100)/c`y'cpindex)    if raxyear==`y' & inrange(tden_,0,1000000)
}
*impute missing values*
charls_eol_impute tden_ if inxt==1, entry_var(tden_o)
*assign to variables*
replace raxtotden1y = tden__i if !mi(tden__i) & inxt==1
replace raxtotden1y = .m if raxtotden1y==. & inxt==1

replace raxtotdenf1y = tden__i_f if !mi(tden__i_f) & inxt==1

drop tden_o tden_min tden_max tden_ tden__i tden__i_f tden__i_neighbor

***oop dental care***
*adjust for cpi*
forvalues y = 2011/2014 {
	replace den_min = ((den_min*100)/c`y'cpindex) if raxyear==`y' & inrange(den_min,0,100000)
	replace den_max = ((den_max*100)/c`y'cpindex) if raxyear==`y' & inrange(den_max,0,100000)
	replace den_    = ((den_*100)/c`y'cpindex)    if raxyear==`y' & inrange(den_,0,1000000)
}
*assign maximum values (already cpi-adjusted)*
replace den_max = raxtotden1y if mi(den_) & !mi(raxtotden1y) & den_o!=0
*impute missing values*
charls_eol_impute den_ if inxt==1, entry_var(den_o)
*assign to variables*
replace raxoopden1y = den__i if !mi(den__i) & inxt==1
replace raxoopden1y = .m if raxoopden1y==. & inxt==1

replace raxoopdenf1y = den__i_f if !mi(den__i_f) & inxt==1

drop den_o den_min den_max den_ den__i den__i_f den__i_neighbor



***total over the counter***
*adjust for cpi*
forvalues y = 2011/2014 {
	replace tdrug1_min = ((tdrug1_min*100)/c`y'cpindex) if raxyear==`y' & inrange(tdrug1_min,0,400000)
	replace tdrug1_max = ((tdrug1_max*100)/c`y'cpindex) if raxyear==`y' & inrange(tdrug1_max,0,400000)
	replace tdrug1_    = ((tdrug1_*100)/c`y'cpindex)    if raxyear==`y' & inrange(tdrug1_,0,1000000)
}
*impute missing values*
charls_eol_impute tdrug1_ if inxt==1, entry_var(tdrug1_o)
*assign to variables*
replace raxtotdrug_1_1y = tdrug1__i if !mi(tdrug1__i) & inxt==1
replace raxtotdrug_1_1y = .m if raxtotdrug_1_1y==. & inxt==1

replace raxtotdrug_1_f1y = tdrug1__i_f if !mi(tdrug1__i_f) & inxt==1

drop tdrug1_o tdrug1_min tdrug1_max tdrug1_ tdrug1__i tdrug1__i_f tdrug1__i_neighbor

***oop over the counter***
*adjust for cpi*
forvalues y = 2011/2014 {
	replace drug1_min = ((drug1_min*100)/c`y'cpindex) if raxyear==`y' & inrange(drug1_min,0,100000)
	replace drug1_max = ((drug1_max*100)/c`y'cpindex) if raxyear==`y' & inrange(drug1_max,0,100000)
	replace drug1_    = ((drug1_*100)/c`y'cpindex)    if raxyear==`y' & inrange(drug1_,0,1000000)
}
*assign maximum values (already cpi-adjusted)*
replace drug1_max = raxtotdrug_1_1y if mi(drug1_) & !mi(raxtotdrug_1_1y) & drug1_o!=0
*impute missing values*
charls_eol_impute drug1_ if inxt==1, entry_var(drug1_o)
*assign to variables*
replace raxoopdrug_1_1y = drug1__i if !mi(drug1__i) & inxt==1
replace raxoopdrug_1_1y = .m if raxoopdrug_1_1y==. & inxt==1

replace raxoopdrug_1_f1y = drug1__i_f if !mi(drug1__i_f) & inxt==1

drop drug1_o drug1_min drug1_max drug1_ drug1__i drug1__i_f drug1__i_neighbor


***total traditional herbs and medicines***
*adjust for cpi*
forvalues y = 2011/2014 {
	replace tdrug3_min = ((tdrug3_min*100)/c`y'cpindex) if raxyear==`y' & inrange(tdrug3_min,0,400000)
	replace tdrug3_max = ((tdrug3_max*100)/c`y'cpindex) if raxyear==`y' & inrange(tdrug3_max,0,400000)
	replace tdrug3_    = ((tdrug3_*100)/c`y'cpindex)    if raxyear==`y' & inrange(tdrug3_,0,1000000)
}
*impute missing values*
charls_eol_impute tdrug3_ if inxt==1, entry_var(tdrug3_o)
*assign to variables*
replace raxtotdrug_3_1y = tdrug3__i if !mi(tdrug3__i) & inxt==1
replace raxtotdrug_3_1y = .m if raxtotdrug_3_1y==. & inxt==1

replace raxtotdrug_3_f1y = tdrug3__i_f if !mi(tdrug3__i_f) & inxt==1

drop tdrug3_o tdrug3_min tdrug3_max tdrug3_ tdrug3__i tdrug3__i_f tdrug3__i_neighbor

***oop traditional herbs and medicines***
*adjust for cpi*
forvalues y = 2011/2014 {
	replace drug3_min = ((drug3_min*100)/c`y'cpindex) if raxyear==`y' & inrange(drug3_min,0,100000)
	replace drug3_max = ((drug3_max*100)/c`y'cpindex) if raxyear==`y' & inrange(drug3_max,0,100000)
	replace drug3_    = ((drug3_*100)/c`y'cpindex)    if raxyear==`y' & inrange(drug3_,0,1000000)
}
*assign maximum values (already cpi-adjusted)*
replace drug3_max = raxtotdrug_3_1y if mi(drug3_) & !mi(raxtotdrug_3_1y) & drug3_o!=0
*impute missing values*
charls_eol_impute drug3_ if inxt==1, entry_var(drug3_o)
*assign to variables*
replace raxoopdrug_3_1y = drug3__i if !mi(drug3__i) & inxt==1
replace raxoopdrug_3_1y = .m if raxoopdrug_3_1y==. & inxt==1

replace raxoopdrug_3_f1y = drug3__i_f if !mi(drug3__i_f) & inxt==1

drop drug3_o drug3_min drug3_max drug3_ drug3__i drug3__i_f drug3__i_neighbor


***total tonic/health supplements***
*adjust for cpi*
forvalues y = 2011/2014 {
	replace tdrug4_min = ((tdrug4_min*100)/c`y'cpindex) if raxyear==`y' & inrange(tdrug4_min,0,400000)
	replace tdrug4_max = ((tdrug4_max*100)/c`y'cpindex) if raxyear==`y' & inrange(tdrug4_max,0,400000)
	replace tdrug4_    = ((tdrug4_*100)/c`y'cpindex)    if raxyear==`y' & inrange(tdrug4_,0,1000000)
}
*impute missing values*
charls_eol_impute tdrug4_ if inxt==1, entry_var(tdrug4_o)
*assign to variables*
replace raxtotdrug_4_1y = tdrug4__i if !mi(tdrug4__i) & inxt==1
replace raxtotdrug_4_1y = .m if raxtotdrug_4_1y==. & inxt==1

replace raxtotdrug_4_f1y = tdrug4__i_f if !mi(tdrug4__i_f) & inxt==1

drop tdrug4_o tdrug4_min tdrug4_max tdrug4_ tdrug4__i tdrug4__i_f tdrug4__i_neighbor

***oop tonic/health supplements***
*adjust ownership*
replace drug4_o = 1 if raxtotdrug_4_f1y==7 & raxtotdrug_4_1y==0 & drug4_o==. //fixing 1 case
*adjust for cpi*
forvalues y = 2011/2014 {
	replace drug4_min = ((drug4_min*100)/c`y'cpindex) if raxyear==`y' & inrange(drug4_min,0,100000)
	replace drug4_max = ((drug4_max*100)/c`y'cpindex) if raxyear==`y' & inrange(drug4_max,0,100000)
	replace drug4_    = ((drug4_*100)/c`y'cpindex)    if raxyear==`y' & inrange(drug4_,0,1000000)
}
*assign maximum values (already cpi-adjusted)*
replace drug4_max = raxtotdrug_4_1y if mi(drug4_) & !mi(raxtotdrug_4_1y) & drug4_o!=0
*impute missing values*
charls_eol_impute drug4_ if inxt==1, entry_var(drug4_o)
*assign to variables*
replace raxoopdrug_4_1y = drug4__i if !mi(drug4__i) & inxt==1
replace raxoopdrug_4_1y = .m if raxoopdrug_4_1y==. & inxt==1

replace raxoopdrug_4_f1y = drug4__i_f if !mi(drug4__i_f) & inxt==1
replace raxoopdrug_4_f1y = 7 if raxtotdrug_4_f1y==7 & raxtotdrug_4_1y==0 //fixing 1 case

drop drug4_o drug4_min drug4_max drug4_ drug4__i drug4__i_f drug4__i_neighbor


***total health care equipment***
*adjust for cpi*
forvalues y = 2011/2014 {
	replace tdrug5_min = ((tdrug5_min*100)/c`y'cpindex) if raxyear==`y' & inrange(tdrug5_min,0,400000)
	replace tdrug5_max = ((tdrug5_max*100)/c`y'cpindex) if raxyear==`y' & inrange(tdrug5_max,0,400000)
	replace tdrug5_    = ((tdrug5_*100)/c`y'cpindex)    if raxyear==`y' & inrange(tdrug5_,0,1000000)
}
*impute missing values*
charls_eol_impute tdrug5_ if inxt==1, entry_var(tdrug5_o)
*assign to variables*
replace raxtotdrug_5_1y = tdrug5__i if !mi(tdrug5__i) & inxt==1
replace raxtotdrug_5_1y = .m if raxtotdrug_5_1y==. & inxt==1

replace raxtotdrug_5_f1y = tdrug5__i_f if !mi(tdrug5__i_f) & inxt==1

drop tdrug5_o tdrug5_min tdrug5_max tdrug5_ tdrug5__i tdrug5__i_f tdrug5__i_neighbor

***oop health care equipment***
*adjust for cpi*
forvalues y = 2011/2014 {
	replace drug5_min = ((drug5_min*100)/c`y'cpindex) if raxyear==`y' & inrange(drug5_min,0,100000)
	replace drug5_max = ((drug5_max*100)/c`y'cpindex) if raxyear==`y' & inrange(drug5_max,0,100000)
	replace drug5_    = ((drug5_*100)/c`y'cpindex)    if raxyear==`y' & inrange(drug5_,0,1000000)
}
*assign maximum values (already cpi-adjusted)*
replace drug5_max = raxtotdrug_5_1y if mi(drug5_) & !mi(raxtotdrug_5_1y) & drug5_o!=0
*impute missing values*
charls_eol_impute drug5_ if inxt==1, entry_var(drug5_o)
*assign to variables*
replace raxoopdrug_5_1y = drug5__i if !mi(drug5__i) & inxt==1
replace raxoopdrug_5_1y = .m if raxoopdrug_5_1y==. & inxt==1

replace raxoopdrug_5_f1y = drug5__i_f if !mi(drug5__i_f) & inxt==1

drop drug5_o drug5_min drug5_max drug5_ drug5__i drug5__i_f drug5__i_neighbor


***Total other medical expenditures***
***total medical expenditures***
replace raxtotome1y_c = (raxtotdrug_1_1y+raxtotdrug_3_1y+raxtotdrug_4_1y+raxtotdrug_5_1y) if inxt==1 
replace raxtotome1y_c = .m if (raxtotome1y_c==.m | (raxtotdrug_1_1y==.m | raxtotdrug_3_1y==.m | raxtotdrug_4_1y==.m | raxtotdrug_5_1y==.m)) & inxt==1

replace raxtotomef1y_c = 6 if (raxtotdrug_1_f1y==6 | raxtotdrug_3_f1y==6 | raxtotdrug_4_f1y==6 | raxtotdrug_5_f1y==6) & inxt==1
replace raxtotomef1y_c = 1 if (raxtotdrug_1_f1y==1 | raxtotdrug_3_f1y==1 | raxtotdrug_4_f1y==1 | raxtotdrug_5_f1y==1) & inxt==1
replace raxtotomef1y_c = 2 if (raxtotdrug_1_f1y==2 | raxtotdrug_3_f1y==2 | raxtotdrug_4_f1y==2 | raxtotdrug_5_f1y==2) & inxt==1
replace raxtotomef1y_c = 3 if (raxtotdrug_1_f1y==3 | raxtotdrug_3_f1y==3 | raxtotdrug_4_f1y==3 | raxtotdrug_5_f1y==3) & inxt==1
replace raxtotomef1y_c = 5 if (raxtotdrug_1_f1y==5 | raxtotdrug_3_f1y==5 | raxtotdrug_4_f1y==5 | raxtotdrug_5_f1y==5) & inxt==1
replace raxtotomef1y_c = 7 if (raxtotdrug_1_f1y==7 | raxtotdrug_3_f1y==7 | raxtotdrug_4_f1y==7 | raxtotdrug_5_f1y==7) & inxt==1
replace raxtotomef1y_c = -1 if (raxtotdrug_1_f1y==-1 | raxtotdrug_3_f1y==-1 | raxtotdrug_4_f1y==-1 | raxtotdrug_5_f1y==-1) & inxt==1
replace raxtotomef1y_c = -2 if (raxtotdrug_1_f1y==-2 | raxtotdrug_3_f1y==-2 | raxtotdrug_4_f1y==-2 | raxtotdrug_5_f1y==-2) & inxt==1

***total oop medical expenditures***
replace raxoopome1y_c = (raxoopdrug_1_1y+raxoopdrug_3_1y+raxoopdrug_4_1y+raxoopdrug_5_1y) if inxt==1 
replace raxoopome1y_c = .m if (raxoopome1y_c==.m | (raxoopdrug_1_1y==.m | raxoopdrug_3_1y==.m | raxoopdrug_4_1y==.m | raxoopdrug_5_1y==.m)) & inxt==1

replace raxoopomef1y_c = 6 if (raxoopdrug_1_f1y==6 | raxoopdrug_3_f1y==6 | raxoopdrug_4_f1y==6 | raxoopdrug_5_f1y==6) & inxt==1
replace raxoopomef1y_c = 1 if (raxoopdrug_1_f1y==1 | raxoopdrug_3_f1y==1 | raxoopdrug_4_f1y==1 | raxoopdrug_5_f1y==1) & inxt==1
replace raxoopomef1y_c = 2 if (raxoopdrug_1_f1y==2 | raxoopdrug_3_f1y==2 | raxoopdrug_4_f1y==2 | raxoopdrug_5_f1y==2) & inxt==1
replace raxoopomef1y_c = 3 if (raxoopdrug_1_f1y==3 | raxoopdrug_3_f1y==3 | raxoopdrug_4_f1y==3 | raxoopdrug_5_f1y==3) & inxt==1
replace raxoopomef1y_c = 5 if (raxoopdrug_1_f1y==5 | raxoopdrug_3_f1y==5 | raxoopdrug_4_f1y==5 | raxoopdrug_5_f1y==5) & inxt==1
replace raxoopomef1y_c = 7 if (raxoopdrug_1_f1y==7 | raxoopdrug_3_f1y==7 | raxoopdrug_4_f1y==7 | raxoopdrug_5_f1y==7) & inxt==1
replace raxoopomef1y_c = -1 if (raxoopdrug_1_f1y==-1 | raxoopdrug_3_f1y==-1 | raxoopdrug_4_f1y==-1 | raxoopdrug_5_f1y==-1) & inxt==1
replace raxoopomef1y_c = -2 if (raxoopdrug_1_f1y==-2 | raxoopdrug_3_f1y==-2 | raxoopdrug_4_f1y==-2 | raxoopdrug_5_f1y==-2) & inxt==1



***TOTAL EXPENDITURE****
***total medical expenditures***
replace raxtotmd1y_c = (raxtotdoc1y + raxtothos1y + raxtotdrug1y + raxtotden1y + raxtotome1y_c) if inxt==1 
replace raxtotmd1y_c = .m if (raxtotmd1y_c==.m | (raxtotdoc1y==.m | raxtothos1y==.m | raxtotdrug1y==.m | raxtotden1y==.m | raxtotome1y_c==.m)) & inxt==1

replace raxtotmdf1y_c = 6 if (raxtotdocf1y==6 | raxtothosf1y==6 | raxtotdrugf1y==6 | raxtotdenf1y==6 | raxtotome1y_c==6) & inxt==1
replace raxtotmdf1y_c = 1 if (raxtotdocf1y==1 | raxtothosf1y==1 | raxtotdrugf1y==1 | raxtotdenf1y==1 | raxtotome1y_c==1) & inxt==1
replace raxtotmdf1y_c = 2 if (raxtotdocf1y==2 | raxtothosf1y==2 | raxtotdrugf1y==2 | raxtotdenf1y==2 | raxtotome1y_c==2) & inxt==1
replace raxtotmdf1y_c = 3 if (raxtotdocf1y==3 | raxtothosf1y==3 | raxtotdrugf1y==3 | raxtotdenf1y==3 | raxtotome1y_c==3) & inxt==1
replace raxtotmdf1y_c = 5 if (raxtotdocf1y==5 | raxtothosf1y==5 | raxtotdrugf1y==5 | raxtotdenf1y==5 | raxtotome1y_c==5) & inxt==1
replace raxtotmdf1y_c = 7 if (raxtotdocf1y==7 | raxtothosf1y==7 | raxtotdrugf1y==7 | raxtotdenf1y==7 | raxtotome1y_c==7) & inxt==1
replace raxtotmdf1y_c = -1 if (raxtotdocf1y==-1 | raxtothosf1y==-1 | raxtotdrugf1y==-1 | raxtotdenf1y==-1 | raxtotome1y_c==-1) & inxt==1
replace raxtotmdf1y_c = -2 if (raxtotdocf1y==-2 | raxtothosf1y==-2 | raxtotdrugf1y==-2 | raxtotdenf1y==-2 | raxtotome1y_c==-2) & inxt==1

***total oop medical expenditures***
replace raxoopmd1y_c = (raxoopdoc1y + raxoophos1y + raxoopdrug1y + raxoopden1y + raxoopome1y_c) if inxt==1 
replace raxoopmd1y_c = .m if (raxoopmd1y_c==.m | (raxoopdoc1y==.m | raxoophos1y==.m | raxoopdrug1y==.m | raxoopden1y==.m | raxoopome1y_c==.m)) & inxt==1

replace raxoopmdf1y_c = 6 if (raxoopdocf1y==6 | raxoophosf1y==6 | raxoopdrugf1y==6 | raxoopdenf1y==6 | raxoopome1y_c==6) & inxt==1
replace raxoopmdf1y_c = 1 if (raxoopdocf1y==1 | raxoophosf1y==1 | raxoopdrugf1y==1 | raxoopdenf1y==1 | raxoopome1y_c==1) & inxt==1
replace raxoopmdf1y_c = 2 if (raxoopdocf1y==2 | raxoophosf1y==2 | raxoopdrugf1y==2 | raxoopdenf1y==2 | raxoopome1y_c==2) & inxt==1
replace raxoopmdf1y_c = 3 if (raxoopdocf1y==3 | raxoophosf1y==3 | raxoopdrugf1y==3 | raxoopdenf1y==3 | raxoopome1y_c==3) & inxt==1
replace raxoopmdf1y_c = 5 if (raxoopdocf1y==5 | raxoophosf1y==5 | raxoopdrugf1y==5 | raxoopdenf1y==5 | raxoopome1y_c==5) & inxt==1
replace raxoopmdf1y_c = 7 if (raxoopdocf1y==7 | raxoophosf1y==7 | raxoopdrugf1y==7 | raxoopdenf1y==7 | raxoopome1y_c==7) & inxt==1
replace raxoopmdf1y_c = -1 if (raxoopdocf1y==-1 | raxoophosf1y==-1 | raxoopdrugf1y==-1 | raxoopdenf1y==-1 | raxoopome1y_c==-1) & inxt==1
replace raxoopmdf1y_c = -2 if (raxoopdocf1y==-2 | raxoophosf1y==-2 | raxoopdrugf1y==-2 | raxoopdenf1y==-2 | raxoopome1y_c==-2) & inxt==1



***Drop unused variables that are not included in the final codebook
drop raxtotdrug_1_1y raxtotdrug_1_f1y raxoopdrug_1_1y raxoopdrug_1_f1y raxtotdrug_3_1y raxtotdrug_3_f1y raxoopdrug_3_1y raxoopdrug_3_f1y raxtotdrug_4_1y raxtotdrug_4_f1y raxoopdrug_4_1y raxoopdrug_4_f1y raxtotdrug_5_1y raxtotdrug_5_f1y raxoopdrug_5_1y raxoopdrug_5_f1y raxtotdoc1y raxoopdoc1y raxtotdocf1y raxoopdocf1y




******************************************************************************************


	
***yes/no cognition***
label define yesnocogs ///
	0 "0.no" ///
	1 "1.yes" ///
	.x ".x:no memory problems"

***Memory Problems***
label define memprob ///
	1 "1.gradual" ///
	2 "2.sudden" ///
	.x ".x:no memory problems"

*set wave number
local wv=2
local pre_wv=1



****merge with wave 2 harmonized CHARLS data***
local cogxt_w2_hcharls rabyear
merge 1:1 ID using "$h_charls", keepusing(`cogxt_w2_hcharls') nogen

*****merge with wave 2 CHARLS Exit Interview***
local cogxt_w2_xt exda007_w2_7 exda007_w2_8_1 exda007_w2_8_2 exda007_w2_9 exda007_w2_10
merge 1:1 ID using "$wave_2_xt", keepusing(`cogxt_w2_xt')

drop if _merge==2
drop _merge

**********************************************************************************

***Memory problems***
*wave 2 respondent memory problems
gen ramprobgs = .
missing exda007_w2_9 exda007_w2_7 if inw`wv'xt==1, result(ramprobgs) wave(`wv')
replace ramprobgs = .x if exda007_w2_7==2
replace ramprobgs = 1 if exda007_w2_9==2
replace ramprobgs = 2 if exda007_w2_9==1
label variable ramprobgs "ramprobgs: r's memory problems gradual or sudden"
label values ramprobgs memprob

*wave 2 respondent memory problems age started to become apparent
gen ramprobage = .
missing exda007_w2_8_1 exda007_w2_8_2 rabyear exda007_w2_7 if inw`wv'xt==1, result(ramprobage) wave(`wv')
replace ramprobage = .x if exda007_w2_7==2
replace ramprobage = (exda007_w2_8_1 - rabyear) if !mi(exda007_w2_8_1) & !mi(rabyear) & inw`wv'xt==1
replace ramprobage = exda007_w2_8_2 if !mi(exda007_w2_8_2)
label variable ramprobage "ramprobage: r's age when memory problems became apparent"

*wave 2 respondent memory problems got worse over time
gen ramprobwrs = .
missing exda007_w2_10 exda007_w2_7 if inw`wv'xt==1, result(ramprobwrs) wave(`wv')
replace ramprobwrs = .x if exda007_w2_7==2
replace ramprobwrs = 0 if exda007_w2_10==2
replace ramprobwrs = 1 if exda007_w2_10==1
label variable ramprobwrs "ramprobwrs: r's memory problems got worse over time"
label values ramprobwrs yesnocogs


**********************************************************************************

***drop Harmonized CHARLS wave 2 variables***
drop `cogxt_w2_hcharls'

****drop CHARLS EOL Exit Interview variables***
drop `cogxt_w2_xt'


******************************************************************************************


	
***yes or no***
label define yesnoeol ///
	0 "0.no" ///
	1 "1.yes" ///
	.w ".w:left no will"
	
***imputation flag eol***
label define flageol ///
  -1 "-1.not imputed, missing neighbors" ///
  -2 "-2.not imputed, missing covariates" ///
	1 "1.continuous value" ///
	2 "2.closed bracket" ///
	3 "3.open bracket" ///
	5 "5.no bracket info" ///
	6 "6.no expense" ///
	7 "7.dk had expense" ///
	.y ".y:yearly amount provided"
	
***imputation flag eol***
label define flageollf ///
  -1 "-1.not imputed, missing neighbors" ///
  -2 "-2.not imputed, missing covariates" ///
	1 "1.continuous value" ///
	2 "2.closed bracket" ///
	3 "3.open bracket" ///
	5 "5.no bracket info" ///
	6 "6.no life ins" ///
	7 "7.dk had life ins" 
	
***imputation flag eol***
label define flageolrec ///
  -1 "-1.not imputed, missing neighbors" ///
  -2 "-2.not imputed, missing covariates" ///
	1 "1.continuous value" ///
	2 "2.closed bracket" ///
	3 "3.open bracket" ///
	5 "5.no bracket info" ///
	6 "6.no monetary gifts" ///
	7 "7.dk received monetary gifts" 
	

***imputation flag eol***
label define flageolinh ///
  -1 "-1.not imputed, missing neighbors" ///
  -2 "-2.not imputed, missing covariates" ///
	1 "1.continuous value" ///
	2 "2.closed bracket" ///
	3 "3.open bracket" ///
	5 "5.no bracket info" ///
	6 "6.no pension inheritance" ///
	7 "7.dk left pension inheritance" 


	

*set wave number
local wv=2
local pre_wv=1



*****merge with wave 2 harmonized CHARLS data***
*local eolxt_w2_hcharls r`pre_wv'pubpen r`pre_wv'peninc r`pre_wv'jcpen
*merge 1:1 ID using "$h_charls", keepusing(`eolxt_w2_hcharls') nogen

******merge with wave 2 CHARLS Weights***
*local eolxt_w2_wt 
*merge 1:m ID using "$wave_2_wt", keepusing(`eolxt_w2_wt')
*
*drop if _merge==2
*drop _merge

*****merge with wave 2 CHARLS Exit Interview***
local eolxt_w2_xt exf016 exf017 exg021 exg022 ///
                  exg023s1 exg023s2 exg023s3 exg023s4 exg023s5 exg023s6 exg023s7 exg023s8 ///
                  exg027 exg028 exg029s1 exg029s2 exg029s3 exg029s4 exg029s5 exg029s6 exg029s7 exg029s8 ///
                  k09 k09_bracket_min k09_bracket_max k01 k02 k03 k03_1 k03_2 k13 k13_bracket_min k13_bracket_max ///
                  zf28 zf29 
                  
merge 1:1 ID using "$wave_2_xt", keepusing(`eolxt_w2_xt') nogen


**********************************************************************************

**Whether insured by life insurance
gen raxlifeins = .
missing exf016 if inw`wv'xt==1, result(raxlifeins)
replace raxlifeins = 0 if exf016==2
replace raxlifeins = 1 if exf016==1 
label variable raxlifeins "raxlifeins: r whether insured by life insurance"
label values raxlifeins yesnoeol

***Value life insurance settlement***
*wave 2 respondent
gen raxlfinsv = .
label variable raxlfinsv "raxlfinsv: r life insurance: total settlement"

*wave 2 respondent flag
gen raxlfinsvf = .
label variable raxlfinsvf "raxlfinsvf: r life insurance flag: total settlement"
label values raxlfinsvf flageollf

**Life insurance settlement imputation
gen tfinsv_o = .
replace tfinsv_o = 0 if raxlifeins==0 & inw`wv'xt==1 
replace tfinsv_o = 1 if raxlifeins==1 & inw`wv'xt==1 

gen tfinsv_ = .
replace tfinsv_ = exf017 if inrange(exf017,0,20000)

gen tfinsv_min = .
gen tfinsv_max = .


**Whether had will (and notarized)
gen rawitwill = .
missing exg021 exg022 if inw`wv'xt==1, result(rawitwill)
replace rawitwill = 0 if exg021==2 | (exg021==1 & exg022==2)
replace rawitwill = 1 if exg021==1 & exg022==1
label variable rawitwill "rawitwill: r had a notarized will"
label values rawitwill yesnoeol

**Whether had will  
gen rawitwill_c = .
missing exg021 if inw`wv'xt==1, result(rawitwill_c)
replace rawitwill_c = 0 if exg021==2 
replace rawitwill_c = 1 if exg021==1 
label variable rawitwill_c "rawitwill_c: r had a will"
label values rawitwill_c yesnoeol
**NOTE: exg022 asks whether the will was notarized, which is similar to having a witnessed will (asked in the HRS). the variable rawitwill_c just asks whether had will


***Spouse is beneficiary in will***
*wave 2 respondent
gen rawillsp = .
missing exg023s1 exg023s2 exg023s3 exg023s4 exg023s5 exg023s6 exg023s7 exg023s8 exg021 if inw`wv'xt==1, result(rawillsp)
replace rawillsp = .w if rawitwill_c==0
replace rawillsp = 0 if (exg023s2==2 | exg023s3==3 | exg023s4==4 | exg023s5==5 | exg023s6==6 | exg023s7==7 | exg023s8==8) & rawitwill_c==1 
replace rawillsp = 1 if exg023s1==1 & rawitwill_c==1
label variable rawillsp "rawillsp: r spouse was beneficiary in will"
label values rawillsp yesnoeol

***Children/Grandchildren are beneficiaries in will***
*wave 2 respondent
gen rawillcg = .
missing exg023s1 exg023s2 exg023s3 exg023s4 exg023s5 exg023s6 exg023s7 exg023s8 exg021 if inw`wv'xt==1, result(rawillcg)
replace rawillcg = .w if rawitwill_c==0
replace rawillcg = 0 if (exg023s1==1 | exg023s3==3 | exg023s4==4 | exg023s6==6 | exg023s7==7 | exg023s8==8) & rawitwill_c==1
replace rawillcg = 1 if (exg023s2==2 | exg023s5==5) & rawitwill_c==1
label variable rawillcg "rawillcg: r children/grandchildren were beneficiaries in will"
label values rawillcg yesnoeol

***Other relatives (including sibilings) are beneficiaries in will***
*wave 2 respondent
gen rawillrl = .
missing exg023s1 exg023s2 exg023s3 exg023s4 exg023s5 exg023s6 exg023s7 exg023s8 exg021 if inw`wv'xt==1, result(rawillrl)
replace rawillrl = .w if rawitwill_c==0
replace rawillrl = 0 if (exg023s1==1 | exg023s2==2 | exg023s5==5 | exg023s6==6 | exg023s7==7 | exg023s8==8) & rawitwill_c==1
replace rawillrl = 1 if (exg023s3==3 | exg023s4==4) & rawitwill_c==1
label variable rawillrl "rawillrl: r other relatives were beneficiaries in will"
label values rawillrl yesnoeol

***Others (including friends) are beneficiaries in will***
*wave 2 respondent
gen rawillot = .
missing exg023s1 exg023s2 exg023s3 exg023s4 exg023s5 exg023s6 exg023s7 exg023s8 exg021 if inw`wv'xt==1, result(rawillot)
replace rawillot = .w if rawitwill_c==0
replace rawillot = 0 if (exg023s1==1 | exg023s2==2 | exg023s3==3 | exg023s4==4 | exg023s5==5 | exg023s7==7) & rawitwill_c==1
replace rawillot = 1 if (exg023s6==6 | exg023s8==8) & rawitwill_c==1
label variable rawillot "rawillot: r others were beneficiaries in will"
label values rawillot yesnoeol

***Charity is beneficiary in will***
*wave 2 respondent
gen rawillin = .
missing exg023s1 exg023s2 exg023s3 exg023s4 exg023s5 exg023s6 exg023s7 exg023s8 exg021 if inw`wv'xt==1, result(rawillin)
replace rawillin = .w if rawitwill_c==0
replace rawillin = 0 if (exg023s1==1 | exg023s2==2 | exg023s3==3 | exg023s4==4 | exg023s5==5 | exg023s6==6 | exg023s8==8) & rawitwill_c==1
replace rawillin = 1 if exg023s7==7 & rawitwill_c==1
label variable rawillin "rawillin: r charity was beneficiary in will"
label values rawillin yesnoeol






***Whether inheritance divided as indicated on will***
*wave 2 respondent
gen rawillfl = .
missing exg028 exg021 if inw`wv'xt==1, result(rawillfl)
replace rawillfl = .w if rawitwill_c==0
replace rawillfl = 0 if exg028==2 & rawitwill_c==1
replace rawillfl = 1 if exg028==1 & rawitwill_c==1
label variable rawillfl "rawillfl: whether r's inheritance divided according to will"
label values rawillfl yesnoeol





***Who actually received the inheritance: if the actual receipients were not different from the ones in the will, then we can assign those values on RABNFCR{..}
***Spouse received inheritance***
*wave 2 respondent
gen rabnfcrsp = .
missing exg029s1 exg029s2 exg029s3 exg029s4 exg029s5 exg029s6 exg029s7 exg029s8 exg027 exg021 exg028 if inw`wv'xt==1, result(rabnfcrsp)
replace rabnfcrsp = 0 if (exg029s2==2 | exg029s3==3 | exg029s4==4 | exg029s5==5 | exg029s6==6 | exg029s7==7 | exg029s8==8) | (rawillsp==0 & rawillfl==1) | exg027==0 
replace rabnfcrsp = 1 if exg029s1==1 | (rawillsp==1 & rawillfl==1)
label variable rabnfcrsp "rabnfcrsp: r spouse was beneficiary of inheritance"
label values rabnfcrsp yesnoeol


***Children/Grandchildren received inheritance***
*wave 2 respondent
gen rabnfcrcg = .
missing exg029s1 exg029s2 exg029s3 exg029s4 exg029s5 exg029s6 exg029s7 exg029s8 exg027 exg021 exg028 if inw`wv'xt==1, result(rabnfcrcg)
replace rabnfcrcg = 0 if (exg029s1==1 | exg029s3==3 | exg029s4==4 | exg029s6==6 | exg029s7==7 | exg029s8==8) | (rawillcg==0 & rawillfl==1) | exg027==0
replace rabnfcrcg = 1 if (exg029s2==2 | exg029s5==5) | (rawillcg==1 & rawillfl==1)
label variable rabnfcrcg "rabnfcrcg: r children/grandchildren were beneficiaries of inheritance"
label values rabnfcrcg yesnoeol

***Other relatives (including sibilings) received inheritance***
*wave 2 respondent
gen rabnfcrrl = .
missing exg029s1 exg029s2 exg029s3 exg029s4 exg029s5 exg029s6 exg029s7 exg029s8 exg027 exg021 exg028 if inw`wv'xt==1, result(rabnfcrrl)
replace rabnfcrrl = 0 if (exg029s1==1 | exg029s2==2 | exg029s5==5 | exg029s6==6 | exg029s7==7 | exg029s8==8) | (rawillrl==0 & rawillfl==1) | exg027==0
replace rabnfcrrl = 1 if (exg029s3==3 | exg029s4==4) | (rawillrl==1 & rawillfl==1)
label variable rabnfcrrl "rabnfcrrl: r other relatives were beneficiaries of inheritance"
label values rabnfcrrl yesnoeol

***Others (including friends) received inheritance***
*wave 2 respondent
gen rabnfcrot = .
missing exg029s1 exg029s2 exg029s3 exg029s4 exg029s5 exg029s6 exg029s7 exg029s8 exg027 exg021 exg028 if inw`wv'xt==1, result(rabnfcrot)
replace rabnfcrot = 0 if (exg029s1==1 | exg029s2==2 | exg029s3==3 | exg029s4==4 | exg029s5==5 | exg029s7==7) | (rawillot==0 & rawillfl==1) | exg027==0
replace rabnfcrot = 1 if (exg029s6==6 | exg029s8==8) | (rawillot==1 & rawillfl==1)
label variable rabnfcrot "rabnfcrot: r others were beneficiaries of inheritance"
label values rabnfcrot yesnoeol

***Charity received inheritance***
*wave 2 respondent
gen rabnfcrin = .
missing exg029s1 exg029s2 exg029s3 exg029s4 exg029s5 exg029s6 exg029s7 exg029s8 exg027 exg021 exg028 if inw`wv'xt==1, result(rabnfcrin)
replace rabnfcrin = 0 if (exg029s1==1 | exg029s2==2 | exg029s3==3 | exg029s4==4 | exg029s5==5 | exg029s6==6 | exg029s8==8) | (rawillin==0 & rawillfl==1) | exg027==0
replace rabnfcrin = 1 if exg029s7==7 | (rawillin==1 & rawillfl==1)
label variable rabnfcrin "rabnfcrin: r charity was beneficiary of inheritance"
label values rabnfcrin yesnoeol



************************
*****EOL Imputation*****
************************

***Value Funeral Costs***
*wave 2 respondent
gen raxfuneral = .
label variable raxfuneral "raxfuneral: r funeral costs"

*wave 2 respondent flag
gen raxfuneralf = .
label variable raxfuneralf "raxfuneralf: r funeral costs flag"
label values raxfuneralf flageol

**Funeral Costs imputation
gen tfuneral_o = .
replace tfuneral_o = 1 if inw`wv'xt==1 

gen tfuneral_ = .
replace tfuneral_ = k09 if inrange(k09,0,100000)

destring k09_bracket_min k09_bracket_max, replace ignore(",")
gen tfuneral_min = .
replace tfuneral_min = 1000 if k09_bracket_min==1000
replace tfuneral_min = 3000 if k09_bracket_min==3000
replace tfuneral_min = 5000 if k09_bracket_min==5000
replace tfuneral_min = 8000 if k09_bracket_min==8000
replace tfuneral_min = 10000 if k09_bracket_min==10000
gen tfuneral_max = .
replace tfuneral_max = 1000 if k09_bracket_max==1000
replace tfuneral_max = 3000 if k09_bracket_max==3000
replace tfuneral_max = 5000 if k09_bracket_max==5000
replace tfuneral_max = 8000 if k09_bracket_max==8000
replace tfuneral_max = 10000 if k09_bracket_max==10000


***Cost burial ground***
*wave 2 respondent
gen raxburial = .
label variable raxburial "raxburial: r burial ground costs"
gen raxburial_y = .y if k03==2 

*wave 2 respondent flag
gen raxburialf = .
label variable raxburialf "raxburialf: r burial ground costs flag"
label values raxburialf flageol

**burial ground costs imputation
gen tburial_o = .
replace tburial_o = 0 if (inlist(k01,3,4,5) | (inlist(k01,1,2) & inlist(k02,1,4,5,6))) & inw`wv'xt==1 
replace tburial_o = 1 if inlist(k01,1,2) & inlist(k02,2,3) & inw`wv'xt==1 

gen tburial_ = .
replace tburial_ = k03_1 if inrange(k03_1,0,46600) & k03==1

gen tburial_min = .
gen tburial_max = .


***Value Gifts/Money received from funeral***
*wave 2 respondent
gen radrecfun = .
label variable radrecfun "radrecfun: r's family value of gifts/money from funeral"

*wave 2 respondent flag
gen radrecfunf = .
label variable radrecfunf "radrecfunf: r's family value of gifts/money from funeral flag"
label values radrecfunf flageolrec

**Gifts/Money received imputation
gen tdrec_o = .
replace tdrec_o = 1 if inw`wv'xt==1 

gen tdrec_ = .
replace tdrec_ = k13 if inrange(k13,0,100000)


destring k13_bracket_min k13_bracket_max, replace ignore(",")
gen tdrec_min = .
replace tdrec_min = 1000 if k13_bracket_min==1000
replace tdrec_min = 3000 if k13_bracket_min==3000
replace tdrec_min = 5000 if k13_bracket_min==5000
replace tdrec_min = 8000 if k13_bracket_min==8000
replace tdrec_min = 10000 if k13_bracket_min==10000
gen tdrec_max = .
replace tdrec_max = 1000 if k13_bracket_max==1000
replace tdrec_max = 3000 if k13_bracket_max==3000
replace tdrec_max = 5000 if k13_bracket_max==5000
replace tdrec_max = 8000 if k13_bracket_max==8000
replace tdrec_max = 10000 if k13_bracket_max==10000

**********************************************************************************

****drop CHARLS EOL Exit Interview variables***
drop `eolxt_w2_xt'


******************************************************************************************





***Life insurance settlement***
*adjust for cpi*
forvalues y = 2011/2014 {
	replace tfinsv_min = ((tfinsv_min*100)/c`y'cpindex) if raxyear==`y' & inrange(tfinsv_min,0,100000)
	replace tfinsv_max = ((tfinsv_max*100)/c`y'cpindex) if raxyear==`y' & inrange(tfinsv_max,0,100000)
	replace tfinsv_    = ((tfinsv_*100)/c`y'cpindex)    if raxyear==`y' & inrange(tfinsv_,0,20000)
}
*impute missing values*
charls_eol_impute tfinsv_ if inxt==1, entry_var(tfinsv_o)
*assign to variables*
replace raxlfinsv = tfinsv__i if !mi(tfinsv__i) & inxt==1
replace raxlfinsv = .m if raxlfinsv==. & inxt==1

replace raxlfinsvf = tfinsv__i_f if !mi(tfinsv__i_f) & inxt==1

drop tfinsv_o tfinsv_min tfinsv_max tfinsv_ tfinsv__i tfinsv__i_f tfinsv__i_neighbor



***Funeral cost***
*adjust for cpi*
forvalues y = 2011/2014 {
	replace tfuneral_min = ((tfuneral_min*100)/c`y'cpindex) if raxyear==`y' & inrange(tfuneral_min,0,10000)
	replace tfuneral_max = ((tfuneral_max*100)/c`y'cpindex) if raxyear==`y' & inrange(tfuneral_max,0,10000)
	replace tfuneral_    = ((tfuneral_*100)/c`y'cpindex)    if raxyear==`y' & inrange(tfuneral_,0,100000)
}
*impute missing values*
charls_eol_impute tfuneral_ if inxt==1, min_var(tfuneral_min) max_var(tfuneral_max) entry_var(tfuneral_o)
*assign to variables*
replace raxfuneral = tfuneral__i if !mi(tfuneral__i) & inxt==1
replace raxfuneral = .m if raxfuneral==. & inxt==1

replace raxfuneralf = tfuneral__i_f if !mi(tfuneral__i_f) & inxt==1


drop tfuneral_o tfuneral_min tfuneral_max tfuneral_ tfuneral__i tfuneral__i_f tfuneral__i_neighbor

***Burial cost***
*adjust for cpi*
forvalues y = 2011/2014 {
	replace tburial_min = ((tburial_min*100)/c`y'cpindex) if raxyear==`y' & inrange(tburial_min,0,10000)
	replace tburial_max = ((tburial_max*100)/c`y'cpindex) if raxyear==`y' & inrange(tburial_max,0,10000)
	replace tburial_    = ((tburial_*100)/c`y'cpindex)    if raxyear==`y' & inrange(tburial_,0,46600)
}
*impute missing values*
charls_eol_impute tburial_ if inxt==1, entry_var(tburial_o)
*assign to variables*
replace raxburial = tburial__i if !mi(tburial__i) & inxt==1
replace raxburial = .m if raxburial==. & inxt==1
replace raxburial = raxburial_y if raxburial_y==.y

replace raxburialf = tburial__i_f if !mi(tburial__i_f) & inxt==1
replace raxburialf = .y if raxburial_y==.y & inxt==1

drop tburial_o tburial_min tburial_max tburial_ tburial__i tburial__i_f tburial__i_neighbor


***Total funeral and burial expenses***
egen radexpense_c = rowtotal(raxburial raxfuneral) if inxt==1 & !mi(raxburial) & !mi(raxfuneral), m
label variable radexpense_c "radexpense_c: r total funeral and burial expenses"
replace radexpense_c = .m if (raxfuneral==.m | raxburial==.m) & inxt==1
replace radexpense_c = .y if raxburial==.y & inxt==1

gen radexpensef_c = .
label variable radexpensef_c "radexpensef_c: r total funeral and burial expenses flag"
replace radexpensef_c = 6 if (raxfuneralf==6 | raxburialf==6) & inxt==1
replace radexpensef_c = 1 if (raxfuneralf==1 | raxburialf==1) & inxt==1
replace radexpensef_c = 2 if (raxfuneralf==2 | raxburialf==2) & inxt==1
replace radexpensef_c = 3 if (raxfuneralf==3 | raxburialf==3) & inxt==1
replace radexpensef_c = 5 if (raxfuneralf==5 | raxburialf==5) & inxt==1
replace radexpensef_c = 7 if (raxfuneralf==7 | raxburialf==7) & inxt==1
replace radexpensef_c = -1 if (raxfuneralf==-1 | raxburialf==-1) & inxt==1
replace radexpensef_c = -2 if (raxfuneralf==-2 | raxburialf==-2) & inxt==1
replace radexpensef_c = .y if raxburialf==.y & inxt==1
label values radexpensef_c flageol

***money/gifts funeral***
*adjust for cpi*
forvalues y = 2011/2014 {
	replace tdrec_min = ((tdrec_min*100)/c`y'cpindex) if raxyear==`y' & inrange(tdrec_min,0,10000)
	replace tdrec_max = ((tdrec_max*100)/c`y'cpindex) if raxyear==`y' & inrange(tdrec_max,0,10000)
	replace tdrec_    = ((tdrec_*100)/c`y'cpindex)    if raxyear==`y' & inrange(tdrec_,0,100000)
}
*impute missing values*
charls_eol_impute tdrec_ if inxt==1, min_var(tdrec_min) max_var(tdrec_max) entry_var(tdrec_o)
*assign to variables*
replace radrecfun = tdrec__i if !mi(tdrec__i) & inxt==1
replace radrecfun = .m if radrecfun==. & inxt==1

replace radrecfunf = tdrec__i_f if !mi(tdrec__i_f) & inxt==1


drop tdrec_o tdrec_min tdrec_max tdrec_ tdrec__i tdrec__i_f tdrec__i_neighbor



***drop unused variables***
drop raxburial_y




******************************************************************************************


	

***yes/no asset***
label define yesnoasset ///
	0 "0.no" ///
	1 "1.yes" ///
	.c ".c:core spouse questions skipped" 
	
***home disposal***
label define dispos ///
	1 "1.inherited" ///
	2 "2.sold" ///
	3 "3.other"  ///
	.c ".c:core spouse questions skipped" ///
	.x ".x:did not own house" 
	
***yes/no asset***
label define yesnoben ///
	0 "0.no" ///
	1 "1.yes" ///
	.c ".c:core spouse questions skipped" ///
	.x ".x:did not own house" ///
	.s ".s:sold or other disposition" 

***imputation flag asset***
label define flagasset ///
  -1 "-1.not imputed, missing neighbors" ///
  -2 "-2.not imputed, missing covariates" ///
	1 "1.continuous value" ///
	2 "2.closed bracket" ///
	3 "3.open bracket" ///
	5 "5.no bracket info" ///
	6 "6.no asset" ///
	7 "7.dk had asset" ///
	.i ".i:records incorrect" ///
	.z ".z:change in ownership, zero percent" 
	
***imputation flag asset for sum and imputed***
label define flagassetsum ///
  1 "1.itemized sum" ///
  2 "2.aggregated report" 
  
  
***imputation flag asset***
label define flagassetpen ///
  -1 "-1.not imputed, missing neighbors" ///
  -2 "-2.not imputed, missing covariates" ///
	1 "1.continuous value" ///
	2 "2.closed bracket" ///
	3 "3.open bracket" ///
	5 "5.no bracket info" ///
	6 "6.no pension" ///
	7 "7.dk received pension" ///
	.i ".i:records incorrect" ///
	.z ".z:change in ownership, zero percent" 


	

*set wave number
local wv=2
local pre_wv=1



****merge with wave 2 harmonized CHARLS data***
local assetxt_w2_hcharls hh2ahousa r1mstat h1coupid r1pubpen r1peninc r1jcpen
merge 1:1 ID using "$h_charls", keepusing(`assetxt_w2_hcharls') nogen

*****merge with wave 2 CHARLS Exit Interview***
local assetxt_w2_xt exg001 exg002 exg003s1 exg003s2 exg003s3 exg003s4 exg003s5 exg003s6 exg003s7 exg006_1 exg008 exg009bracket_min exg009bracket_max ///
                    exg010_1_ exg010_2_ ///
                    exf005_1_ exf005_2_ exf005_3_ exf005_4_ exf005_5_ exf005_6_ exf005_7_ ///
                  	exf005_1_1_ exf005_1_2_ exf005_1_3_ exf005_1_4_ exf005_1_5_ exf005_1_6_ exf005_1_7_ ///
                  	exf006_1_ exf006_2_ exf006_4_ exf006_5_ exf006_6_ exf006_7_ ///
                  	exf007_1_ exf007_2_ exf007_4_ exf007_5_ exf007_6_ exf007_7_ ///
                  	exf008 exf011_1_ exf011_2_ exf011_4_ exf011_5_ exf011_6_ exf011_7_ ///
                  	exf011_8_ exf011_9_ exf011_10_ exf011_11_ exf011_12_ ///
                  	exf013_1_ exf013_2_ exf013_6_ exf013_8_ exf013_9_ exf013_11_ exf013_12_ ///
                    exf014 exf015 ///
                    exg019 exg019_1 exg020_1 exg020_2 exg020_3 exg020_4 exg027 ///
                    exg003s1 exg003s2 exg003s3 exg003s4 exg003s5 exg003s6 exg003s7
merge 1:1 ID using "$wave_2_xt", keepusing(`assetxt_w2_xt') nogen

***merge with wave 1 core data***
local assetxt_w1_wp fn001
merge m:1 ID_w1 using "$w1_wp", keepusing(`assetxt_w1_wp') nogen

***merge with wave 1 core data***
local assetxt_w1_hi ha027 ha028
merge m:1 householdID_w1 using "$w1_hi", keepusing(`assetxt_w1_hi') nogen

***merge with wave 2 core data***
local assetxt_w2_hi ha007 ha007_w2_1 ha007_w2_2 ha007_w2_3s1 ha007_w2_3s2 ha007_w2_3s3 ha007_w2_3s4 ha007_w2_3s5 ha007_w2_3s6 ha007_w2_3s7 ha007_w2_3s8 
merge m:1 householdID using "$wave_2_hi", keepusing(`assetxt_w2_hi') nogen



**********************************************************************************

***Whether owned home at death***
*wave 2 respondent whether owned home at death
gen raxahown = .
missing exg001 if inw`wv'xt==1, result(raxahown)
replace raxahown = .c if exg001==. & radmarrp==1 & ha007_w2_1==. & inw`wv'xt==1 //core questions skipped for spouse
replace raxahown = 0 if exg001==3 //records incorrect
replace raxahown = 0 if exg001==. & ha007_w2_1==1 & ha007_w2_2==0 & inw`wv'xt==1 //change in ownership but owned zero percent
replace raxahown = 0 if exg001==2 | (ha007_w2_1==2 & exg001==. & inw`wv'xt==1)
replace raxahown = 1 if exg001==1 | (inrange(ha007_w2_2,1,100) & exg001==. & inw`wv'xt==1)
label variable raxahown "raxahown: r owned home at death"
label values raxahown yesnoasset
*there are 2 cases where ha007_w2==1 & ha007_w2_2==. (ownership changed, but no percentage reported)

***What happened to home after death***
*wave 2 respondent what happened to home after death
gen raxhomedis_c = .
missing exg002 raxahown if inw`wv'xt==1, result(raxhomedis_c)
replace raxhomedis_c = .c if raxahown==.c & inw`wv'xt==1
replace raxhomedis_c = .x if raxahown==0 & inw`wv'xt==1
replace raxhomedis_c = 1 if (exg002==1 | ///
														(ha007_w2_3s1==1 | ha007_w2_3s2==2 | ha007_w2_3s3==3 | ha007_w2_3s4==4 | ///
														 ha007_w2_3s5==5 | ha007_w2_3s6==6 | ha007_w2_3s7==7 | ha007_w2_3s8==8))  & raxahown==1
replace raxhomedis_c = 2 if exg002==2 & raxahown==1
replace raxhomedis_c = 3 if exg002==3 & raxahown==1
label variable raxhomedis_c "raxhomedis_c: disposition of r's home"
label values raxhomedis_c dispos

***Main House: Beneficiaries
**Spouse is hereditary of house
*wave 2 respondent
gen raxhomesp = .
missing exg001 ha007_w2_1 ha007_w2_2 ha007_w2_3s1 ha007_w2_3s2 ha007_w2_3s3 ha007_w2_3s4 ha007_w2_3s5 ha007_w2_3s6 ha007_w2_3s7 ha007_w2_3s8 exg003s1 exg003s2 exg003s3 exg003s4 exg003s5 exg003s6 exg003s7 if inw`wv'xt==1, result(raxhomesp)
replace raxhomesp = .c if raxahown==.c & inw`wv'xt==1
replace raxhomesp = .x if raxahown==0 & inw`wv'xt==1
replace raxhomesp = .s if inlist(raxhomedis_c,2,3) & inw`wv'xt==1
replace raxhomesp = 0 if raxhomedis_c==1 & ((ha007_w2_3s2==2 | ha007_w2_3s3==3 | ha007_w2_3s4==4 | ha007_w2_3s5==5 | ha007_w2_3s6==6 | ///
                                             ha007_w2_3s7==7 | ha007_w2_3s8==8) | ///
                                            (exg003s1==1 | exg003s2==2 | exg003s3==3 | exg003s4==4 | exg003s5==5 | exg003s6==6 | exg003s7==7))
replace raxhomesp = 1 if raxhomedis_c==1 & ha007_w2_3s1==1
label variable raxhomesp "raxhomesp: r whether spouse inherited main house"
label values raxhomesp yesnoben

**Children or grandchildren are hereditaries of house
*wave 2 respondent
gen raxhomech = .
missing exg001 ha007_w2_1 ha007_w2_2 ha007_w2_3s1 ha007_w2_3s2 ha007_w2_3s3 ha007_w2_3s4 ha007_w2_3s5 ha007_w2_3s6 ha007_w2_3s7 ha007_w2_3s8 exg003s1 exg003s2 exg003s3 exg003s4 exg003s5 exg003s6 exg003s7 if inw`wv'xt==1, result(raxhomech)
replace raxhomech = .c if raxahown==.c & inw`wv'xt==1
replace raxhomech = .x if raxahown==0 & inw`wv'xt==1
replace raxhomech = .s if inlist(raxhomedis_c,2,3) & inw`wv'xt==1
replace raxhomech = 0 if raxhomedis_c==1 & ((ha007_w2_3s1==1 | ha007_w2_3s3==3 | ha007_w2_3s4==4 | ha007_w2_3s6==6 | ///
                                             ha007_w2_3s7==7 | ha007_w2_3s8==8) | ///
                                            (exg003s2==2 | exg003s3==3 | exg003s5==5 | exg003s6==6 | exg003s7==7))
replace raxhomech = 1 if raxhomedis_c==1 & ((ha007_w2_3s2==2  | ha007_w2_3s5==5) | (exg003s1==1 | exg003s4==4))
label variable raxhomech "raxhomech: r whether children inherited main house"
label values raxhomech yesnoben

**Relatives are hereditaries of house
*wave 2 respondent
gen raxhomerl = .
missing exg001 ha007_w2_1 ha007_w2_2 ha007_w2_3s1 ha007_w2_3s2 ha007_w2_3s3 ha007_w2_3s4 ha007_w2_3s5 ha007_w2_3s6 ha007_w2_3s7 ha007_w2_3s8 exg003s1 exg003s2 exg003s3 exg003s4 exg003s5 exg003s6 exg003s7 if inw`wv'xt==1, result(raxhomerl)
replace raxhomerl = .c if raxahown==.c & inw`wv'xt==1
replace raxhomerl = .x if raxahown==0 & inw`wv'xt==1
replace raxhomerl = .s if inlist(raxhomedis_c,2,3) & inw`wv'xt==1
replace raxhomerl = 0 if raxhomedis_c==1 & ((ha007_w2_3s1==1 | ha007_w2_3s2==2 | ha007_w2_3s5==5 | ha007_w2_3s6==6 | ///
                                             ha007_w2_3s7==7 | ha007_w2_3s8==8) | ///
                                            (exg003s1==1 | exg003s4==4 | exg003s5==5 | exg003s6==6 | exg003s7==7))
replace raxhomerl = 1 if raxhomedis_c==1 & ((ha007_w2_3s3==3 | ha007_w2_3s4==4) | (exg003s2==2 | exg003s3==3))
label variable raxhomerl "raxhomerl: r whether relatives inherited main house"
label values raxhomerl yesnoben

**Others (including friends) are hereditaries of house
*wave 2 respondent
gen raxhomeot = .
missing exg001 ha007_w2_1 ha007_w2_2 ha007_w2_3s1 ha007_w2_3s2 ha007_w2_3s3 ha007_w2_3s4 ha007_w2_3s5 ha007_w2_3s6 ha007_w2_3s7 ha007_w2_3s8 exg003s1 exg003s2 exg003s3 exg003s4 exg003s5 exg003s6 exg003s7 if inw`wv'xt==1, result(raxhomeot)
replace raxhomeot = .c if raxahown==.c & inw`wv'xt==1
replace raxhomeot = .x if raxahown==0 & inw`wv'xt==1
replace raxhomeot = .s if inlist(raxhomedis_c,2,3) & inw`wv'xt==1
replace raxhomeot = 0 if raxhomedis_c==1 & ((ha007_w2_3s1==1 | ha007_w2_3s2==2 | ha007_w2_3s3==3 | ha007_w2_3s4==4 | ha007_w2_3s5==5 | ///
                                             ha007_w2_3s7==7) | ///
                                            (exg003s1==1 | exg003s2==2 | exg003s3==3 | exg003s4==4 | exg003s6==6))
replace raxhomeot = 1 if raxhomedis_c==1 & ((ha007_w2_3s6==6 | ha007_w2_3s8==8) | (exg003s5==5 | exg003s7==7))
label variable raxhomeot "raxhomeot: r whether others inherited main house"
label values raxhomeot yesnoben

**Charity is hereditary of house
*wave 2 respondent
gen raxhomein = .
missing exg001 ha007_w2_1 ha007_w2_2 ha007_w2_3s1 ha007_w2_3s2 ha007_w2_3s3 ha007_w2_3s4 ha007_w2_3s5 ha007_w2_3s6 ha007_w2_3s7 ha007_w2_3s8 exg003s1 exg003s2 exg003s3 exg003s4 exg003s5 exg003s6 exg003s7 if inw`wv'xt==1, result(raxhomein)
replace raxhomein = .c if raxahown==.c & inw`wv'xt==1
replace raxhomein = .x if raxahown==0 & inw`wv'xt==1
replace raxhomein = .s if inlist(raxhomedis_c,2,3) & inw`wv'xt==1
replace raxhomein = 0 if raxhomedis_c==1 & ((ha007_w2_3s1==1 | ha007_w2_3s2==2 | ha007_w2_3s3==3 | ha007_w2_3s4==4 | ha007_w2_3s5==5 | ///
                                             ha007_w2_3s6==6 | ha007_w2_3s8==8) | ///
                                            (exg003s1==1 | exg003s2==2 | exg003s3==3 | exg003s4==4 | exg003s5==5| exg003s7==7))
replace raxhomein = 1 if raxhomedis_c==1 & (ha007_w2_3s7==7 | exg003s6==6)
label variable raxhomein "raxhomein: r whether charity inherited main house"
label values raxhomein yesnoben





***Value of home***
gen raxahous = .
label variable raxahous "raxahous: r asset: primary residence"

gen raxafhous = .
label variable raxafhous "raxafhous: r asset flag: primary residence"
label values raxafhous flagasset

gen hous_o = .
replace hous_o = 0 if raxahown==0 & inw`wv'xt==1
replace hous_o = 1 if raxahown==1 & inw`wv'xt==1 

gen hh2ahousa_ = .
forvalues p = 1 / 3 {
	bysort householdID: replace hh2ahousa_ = hh2ahousa[_n+`p'] if !mi(householdID) & hh2ahousa[_n+`p'] !=.
	bysort householdID: replace hh2ahousa_ = hh2ahousa[_n-`p'] if !mi(householdID) & hh2ahousa[_n-`p'] !=. 
}

gen hous_ = .
replace hous_ = exg008*10000 if inrange(exg008,0,99)
replace hous_ = exg008 if inrange(exg008,100,700000)
*replace hous_ = exg006_1 if inrange(exg006_1,0,...) //No observations in this wave
replace hous_ = hh2ahousa_ if inrange(hh2ahousa_,0,5000000) & hous_o==1 & (exg008==. & exg006_1==.)

destring exg009bracket_min exg009bracket_max, replace ignore(",")

gen hous_max = .
replace hous_max = exg009bracket_max if inrange(exg009bracket_max,0,1000000)
gen hous_min = .
replace hous_min = exg009bracket_min if inrange(exg009bracket_min,0,1000000)
*setting min and max to (.) if the minimum is greater than the maximum
replace hous_max = . if exg009bracket_max==200000 & exg009bracket_min==500000
replace hous_min = . if exg009bracket_max==200000 & exg009bracket_min==500000


***Whether owned other home different from main at death*** 
*wave 2 respondent whether owned another home at death
gen raxarlesf = .
missing exg010_1_ exg010_2_ ha027 ha028 if inw`wv'xt==1, result(raxarlesf)
replace raxarlesf = 0 if exg010_1_==3 | exg010_2_==3 //records incorrect
replace raxarlesf = 0 if ha027==2 | ha028==0 | exg010_1_==2 | exg010_2_==2
replace raxarlesf = 1 if exg010_1_==1 | exg010_2_==1 
label variable raxarlesf "raxarlesf: r asset flag: ownership of other real estate"
label values raxarlesf yesnoasset




***Intermediate non-imputed pension inheritance variables
**Whether received pension inheritance from program disclosed in previous core wave
gen temp_inhpen_pre = .
missing exf005_1_ exf005_2_ exf005_3_ exf005_4_ exf005_5_ exf005_6_ exf005_7_ fn001 if inw`wv'xt==1, result(temp_inhpen_pre)
replace temp_inhpen_pre = 0 if fn001==2 & inw`wv'xt==1
replace temp_inhpen_pre = 0 if exf005_1_==2 | exf005_2_==2 | exf005_3_==2 | exf005_4_==2 | exf005_5_==2 | exf005_6_==2 | exf005_7_==2 | ///
															 exf006_1_==2 | exf006_2_==2 | exf006_4_==2 | exf006_5_==2 | exf006_6_==2 | exf006_7_==2 //added for no payment
replace temp_inhpen_pre = 1 if exf005_1_==1 | exf005_2_==1 | exf005_3_==1 | exf005_4_==1 | exf005_5_==1 | exf005_6_==1 | exf005_7_==1 | ///
															 exf006_1_==1 | exf006_2_==1 | exf006_4_==1 | exf006_5_==1 | exf006_6_==1 | exf006_7_==1
**Amount received from program disclosed in previous core wave
egen temp_totinhpen_pre = rowtotal(exf005_1_1_ exf005_1_2_ exf005_1_3_ exf005_1_4_ exf005_1_5_ exf005_1_6_ exf005_1_7_ ///
																	 exf007_1_ exf007_2_ exf007_4_ exf007_5_ exf007_6_ exf007_7_)  if inw`wv'xt==1, m 


**Whether received pension inheritance from other program other than the one disclosed in previous core wave
gen temp_inhpen_oth = .
missing exf008 if inw`wv'xt==1, result(temp_inhpen_oth)
replace temp_inhpen_oth = 0 if exf008==2
replace temp_inhpen_oth = 1 if exf008==1 
**Whether received pension inheritance from other program other than the one disclosed in previous core wave (Note: variable exf011_3_ NOT present in the dataset - excluded)
egen temp_totinhpen_oth = rowtotal(exf011_1_ exf011_2_ exf011_4_ exf011_5_ exf011_6_ exf011_7_ exf011_8_ exf011_9_ exf011_10_ exf011_11_ exf011_12_ ///
																	 exf013_1_ exf013_2_ exf013_6_ exf013_8_ exf013_9_ exf013_11_ exf013_12_) if inw`wv'xt==1, m

**whether received other lump sum = .
gen temp_inhpen_ols = .
missing exf014 if inw`wv'xt==1, result(temp_inhpen_ols)
replace temp_inhpen_ols = 0 if exf014==2
replace temp_inhpen_ols = 1 if exf014==1
***amount
gen temp_totinhpen_ols = exf015 if inrange(exf015,100,75000)


**Pension inheritance imputation
*temp_inhpen_pre
gen raxapen_pre = .
gen raxafpen_pre = .
label values raxafpen_pre flageolinh

gen tinhpen_pre_o = .
replace tinhpen_pre_o = 0 if temp_inhpen_pre==0 & inw`wv'xt==1
replace tinhpen_pre_o = 1 if temp_inhpen_pre==1 & inw`wv'xt==1 

gen tinhpen_pre_ = .
replace tinhpen_pre_ = temp_totinhpen_pre if inrange(temp_totinhpen_pre,0,700000) & inw`wv'xt==1

gen tinhpen_pre_min = .
gen tinhpen_pre_max = .

*temp_inhpen_oth
gen raxapen_oth = .
gen raxafpen_oth = .
label values raxafpen_oth flageolinh

gen tinhpen_oth_o = .
replace tinhpen_oth_o = 0 if temp_inhpen_oth==0 & inw`wv'xt==1
replace tinhpen_oth_o = 1 if temp_inhpen_oth==1 & inw`wv'xt==1 

gen tinhpen_oth_ = .
replace tinhpen_oth_ = temp_totinhpen_oth if inrange(temp_totinhpen_oth,0,700000) & inw`wv'xt==1

gen tinhpen_oth_min = .
gen tinhpen_oth_max = .

*temp_inhpen_ols
gen raxapen_ols = .
gen raxafpen_ols = .
label values raxafpen_ols flageolinh

gen tinhpen_ols_o = .
replace tinhpen_ols_o = 0 if temp_inhpen_ols==0 & inw`wv'xt==1
replace tinhpen_ols_o = 1 if temp_inhpen_ols==1 & inw`wv'xt==1 

gen tinhpen_ols_ = .
replace tinhpen_ols_ = temp_totinhpen_ols if inrange(temp_totinhpen_ols,0,700000) & inw`wv'xt==1

gen tinhpen_ols_min = .
gen tinhpen_ols_max = .

****drop temporary variables for imputation
drop temp_inhpen_pre temp_totinhpen_pre temp_inhpen_oth temp_totinhpen_oth temp_inhpen_ols temp_totinhpen_ols


***Value of other inheritance (excluding real estate, including only medical insurance account; pension and compensation; other compensation;life insurance payment)***
*Generate temporary variable to add if exg019==2
gen exg019_1_imput = .
gen exg019_1_fimput = .
label values exg019_1_fimput flagassetpen

gen oinher_o = .
replace oinher_o = 0 if inlist(exg019_1,0,.) & inw`wv'xt==1
replace oinher_o = 1 if inrange(exg019_1,0,150000) & inw`wv'xt==1 

gen oinher_ = .
replace oinher_ = exg019_1 if inrange(exg019_1,0,150000)

gen oinher_max = .
gen oinher_min = .



***Value of other inheritance (financial assets)***
*generate total inherited (reported sum of values)
*generate variable 1
gen raxafnas1 = .
gen raxaffnas1 = .
label values raxaffnas1 flagasset

gen afnas1_o = .
replace afnas1_o = 0 if exg020_1==0 & inw`wv'xt==1
replace afnas1_o = 1 if inrange(exg020_1,1,600000) & inw`wv'xt==1 

gen afnas1_ = .
replace afnas1_ = exg020_1 if inrange(exg020_1,0,600000)

gen afnas1_max = .
gen afnas1_min = .

*generate variable 2
gen raxafnas2 = .
gen raxaffnas2 = .
label values raxaffnas2 flagasset

gen afnas2_o = .
replace afnas2_o = 0 if exg020_2==0 & inw`wv'xt==1
replace afnas2_o = 1 if inrange(exg020_2,1,600000) & inw`wv'xt==1 

gen afnas2_ = .
replace afnas2_ = exg020_2 if inrange(exg020_2,0,600000)

gen afnas2_max = .
gen afnas2_min = .

*generate variable 3
gen raxafnas3 = .
gen raxaffnas3 = .
label values raxaffnas3 flagasset

gen afnas3_o = .
replace afnas3_o = 0 if exg020_3==0 & inw`wv'xt==1
replace afnas3_o = 1 if inrange(exg020_3,1,600000) & inw`wv'xt==1 

gen afnas3_ = .
replace afnas3_ = exg020_3 if inrange(exg020_3,0,600000)

gen afnas3_max = .
gen afnas3_min = .


*generate variable 4 (physical assets)
gen raxaphas = .
label variable raxaphas "raxaphas: r asset: physical assets inheritance"
gen raxafphas = .
label variable raxafphas "raxafphas: r asset flag: physical assets inheritance"
label values raxafphas flagasset

gen aphas_o = .
replace aphas_o = 0 if exg020_4==0 & inw`wv'xt==1
replace aphas_o = 1 if inrange(exg020_4,1,600000) & inw`wv'xt==1 

gen aphas_ = .
replace aphas_ = exg020_4 if inrange(exg020_4,0,600000)

gen aphas_max = .
gen aphas_min = .




***Value Total Assets***
*wave 2 respondent
gen raxatotb = .
label variable raxatotb "raxatotb: r asset: total assets"

*wave 2 respondent flag
gen raxaftotb = .
label variable raxaftotb "raxaftotb: r asset flag: total assets"
label values raxaftotb flagasset

***Value Total Non-housing Assets***
*wave 2 respondent
gen raxatotn = .
label variable raxatotn "raxatotn: r asset: total non-housing assets"

*wave 2 respondent flag
gen raxaftotn = .
label variable raxaftotn "raxaftotn: r asset flag: total non-housing assets"
label values raxaftotn flagasset

*Total reported for imputation
gen exg027_imput = .
gen exg027_fimput = .
label values exg027_fimput flagasset

gen exg027_o = .
replace exg027_o = 1 if inw`wv'xt==1 

gen exg027_ = .
replace exg027_ = exg027 if inrange(exg027,-10000,600000)

gen exg027_max = .
gen exg027_min = .


**Generate temporary variable for add file
gen total = exg019


**********************************************************************************

****drop Harmonized CHARLS wave 2 variables***
drop `assetxt_w2_hcharls' hh2ahousa

****drop CHARLS EOL Weights variables***
*drop `assetxt_w2_wt'

****drop CHARLS EOL Exit Interview variables*** 
drop `assetxt_w2_xt' 

****drop CHARLS EOL Wave 1 Core WP variables*** 
drop `assetxt_w1_wp' 

****drop CHARLS EOL Wave 1 Core HI variables*** 
drop `assetxt_w1_hi' 

****drop CHARLS EOL Wave 2 Core HI variables*** 
drop `assetxt_w2_hi' 

*****drop CHARLS EOL Verbal Autopsy variables***
*drop `assetxt_w2_va'

***drop temporary variables***
drop hh2ahousa_

******************************************************************************************





***primary residence***
*adjust for cpi*
forvalues y = 2011/2014 {
	replace hous_min = ((hous_min*100)/c`y'cpindex) if raxyear==`y' & inrange(hous_min,0,500000)
	replace hous_max = ((hous_max*100)/c`y'cpindex) if raxyear==`y' & inrange(hous_max,0,2000000)
	replace hous_    = ((hous_*100)/c`y'cpindex)    if raxyear==`y' & inrange(hous_,0,700000)
}
*impute missing values*
charls_eol_impute hous_ if inxt==1, entry_var(hous_o)
*assign to variables*
replace raxahous = hous__i if !mi(hous__i) & inxt==1 & !inlist(raxahous,.i,.z)
replace raxahous = .m if raxahous==. & inxt==1

replace raxafhous = hous__i_f if !mi(hous__i_f) & inxt==1 & !inlist(raxafhous,.i,.z)
replace raxafhous = .i if raxafhous==.i & inxt==1
replace raxafhous = .z if raxafhous==.z & inxt==1

drop hous_o hous_min hous_max hous_ hous__i hous__i_f hous__i_neighbor

***Pension Inheritance*** (pre component)
*adjust for cpi*
forvalues y = 2011/2014 {
	replace tinhpen_pre_min = ((tinhpen_pre_min*100)/c`y'cpindex) if raxyear==`y' & inrange(tinhpen_pre_min,0,100000)
	replace tinhpen_pre_max = ((tinhpen_pre_max*100)/c`y'cpindex) if raxyear==`y' & inrange(tinhpen_pre_max,0,100000)
	replace tinhpen_pre_    = ((tinhpen_pre_*100)/c`y'cpindex)    if raxyear==`y' & inrange(tinhpen_pre_,0,700000)
}
*impute missing values*
charls_eol_impute tinhpen_pre_ if inxt==1, entry_var(tinhpen_pre_o)
*assign to variables*
replace raxapen_pre = tinhpen_pre__i if !mi(tinhpen_pre__i) & inxt==1
replace raxapen_pre = .m if raxapen_pre==. & inxt==1

replace raxafpen_pre = tinhpen_pre__i_f if !mi(tinhpen_pre__i_f) & inxt==1

drop tinhpen_pre_o tinhpen_pre_min tinhpen_pre_max tinhpen_pre_ tinhpen_pre__i tinhpen_pre__i_f tinhpen_pre__i_neighbor

***Pension Inheritance*** (oth component)
*adjust for cpi*
forvalues y = 2011/2014 {
	replace tinhpen_oth_min = ((tinhpen_oth_min*100)/c`y'cpindex) if raxyear==`y' & inrange(tinhpen_oth_min,0,100000)
	replace tinhpen_oth_max = ((tinhpen_oth_max*100)/c`y'cpindex) if raxyear==`y' & inrange(tinhpen_oth_max,0,100000)
	replace tinhpen_oth_    = ((tinhpen_oth_*100)/c`y'cpindex)    if raxyear==`y' & inrange(tinhpen_oth_,0,700000)
}
*impute missing values*
charls_eol_impute tinhpen_oth_ if inxt==1, entry_var(tinhpen_oth_o)
*assign to variables*
replace raxapen_oth = tinhpen_oth__i if !mi(tinhpen_oth__i) & inxt==1
replace raxapen_oth = .m if raxapen_oth==. & inxt==1

replace raxafpen_oth = tinhpen_oth__i_f if !mi(tinhpen_oth__i_f) & inxt==1

drop tinhpen_oth_o tinhpen_oth_min tinhpen_oth_max tinhpen_oth_ tinhpen_oth__i tinhpen_oth__i_f tinhpen_oth__i_neighbor

***Pension Inheritance*** (ols component)
*adjust for cpi*
forvalues y = 2011/2014 {
	replace tinhpen_ols_min = ((tinhpen_ols_min*100)/c`y'cpindex) if raxyear==`y' & inrange(tinhpen_ols_min,0,100000)
	replace tinhpen_ols_max = ((tinhpen_ols_max*100)/c`y'cpindex) if raxyear==`y' & inrange(tinhpen_ols_max,0,100000)
	replace tinhpen_ols_    = ((tinhpen_ols_*100)/c`y'cpindex)    if raxyear==`y' & inrange(tinhpen_ols_,0,700000)
}
*impute missing values*
charls_eol_impute tinhpen_ols_ if inxt==1, entry_var(tinhpen_ols_o)
*assign to variables*
replace raxapen_ols = tinhpen_ols__i if !mi(tinhpen_ols__i) & inxt==1
replace raxapen_ols = .m if raxapen_ols==. & inxt==1

replace raxafpen_ols = tinhpen_ols__i_f if !mi(tinhpen_ols__i_f) & inxt==1

drop tinhpen_ols_o tinhpen_ols_min tinhpen_ols_max tinhpen_ols_ tinhpen_ols__i tinhpen_ols__i_f tinhpen_ols__i_neighbor

***ADD ALL 3 PENSION INHERITANCE' VARIABLES TOGETHER
gen raxapen = raxapen_pre + raxapen_oth + raxapen_ols if inxt==1
replace raxapen = .m if raxapen==. & inxt==1
label variable raxapen "raxapen: r total inheritance: pension inheritance"

gen raxafpen = .
label variable raxafpen "raxafpen: r total inheritance flag: pension inheritance"
label values raxafpen flagasset


replace raxafpen = 6 if (raxafpen_pre==6 | raxafpen_oth==6 | raxafpen_ols==6) & inxt==1
replace raxafpen = 1 if (raxafpen_pre==1 | raxafpen_oth==1 | raxafpen_ols==1) & inxt==1
replace raxafpen = 2 if (raxafpen_pre==2 | raxafpen_oth==2 | raxafpen_ols==2) & inxt==1
replace raxafpen = 3 if (raxafpen_pre==3 | raxafpen_oth==3 | raxafpen_ols==3) & inxt==1
replace raxafpen = 5 if (raxafpen_pre==5 | raxafpen_oth==5 | raxafpen_ols==5) & inxt==1
replace raxafpen = 7 if (raxafpen_pre==7 | raxafpen_oth==7 | raxafpen_ols==7) & inxt==1
replace raxafpen = -1 if (raxafpen_pre==-1 | raxafpen_oth==-1 | raxafpen_ols==-1) & inxt==1
replace raxafpen = -2 if (raxafpen_pre==-2 | raxafpen_oth==-2 | raxafpen_ols==-2) & inxt==1




***other inheritance***
*adjust for cpi*
forvalues y = 2011/2014 {
	replace oinher_min = ((oinher_min*100)/c`y'cpindex) if raxyear==`y' & inrange(oinher_min,0,500000)
	replace oinher_max = ((oinher_max*100)/c`y'cpindex) if raxyear==`y' & inrange(oinher_max,0,2000000)
	replace oinher_    = ((oinher_*100)/c`y'cpindex)    if raxyear==`y' & inrange(oinher_,0,150000)
}
*impute missing values*
charls_eol_impute oinher_ if inxt==1, entry_var(oinher_o)
*assign to variables*
replace exg019_1_imput = oinher__i if !mi(oinher__i) & inxt==1
replace exg019_1_imput = .m if exg019_1_imput==. & inxt==1

replace exg019_1_fimput = oinher__i_f if !mi(oinher__i_f) & inxt==1

drop oinher_o oinher_min oinher_max oinher_ oinher__i oinher__i_f oinher__i_neighbor

*generate sum
gen penlf = raxapen + raxlfinsv if inxt==1
egen maxplf = rowmax(penlf exg019_1_imput) if inxt==1
replace total = 3 if penlf>=exg019_1_imput & !mi(penlf) & !mi(exg019_1_imput) & total==. & inxt==1
replace total = 4 if ((penlf<exg019_1_imput & !mi(penlf) & !mi(exg019_1_imput)) | (penlf==. & !mi(exg019_1_imput))) & total==. & inxt==1


*replace to sum
gen raxapenlf = .
replace raxapenlf = penlf if !mi(penlf) & total==1 & inxt==1 //sum if sum total was correct
replace raxapenlf = exg019_1_imput if total==2 & inxt==1 //new total if sum total was incorrect
replace raxapenlf = maxplf if inlist(total,3,4) & inxt==1 //max of sum total and new total if total was missing
replace raxapenlf = .m if ((raxapen==.m & raxlfinsv==.m & total==.) | ((raxapen==.m | raxlfinsv==.m) & total==1)) & inxt==1
label variable raxapenlf "raxapenlf: r asset: pension + life ins + other inheritance"

gen raxafpenlf = .
label variable raxafpenlf "raxafpenlf: r asset flag: pension + life ins + other inheritance"
label values raxafpenlf flagasset


replace raxafpenlf = 6 if (raxafpen==6 | raxlfinsvf==6) & inlist(total,1,3) & inxt==1
replace raxafpenlf = 1 if (raxafpen==1 | raxlfinsvf==1) & inlist(total,1,3) & inxt==1
replace raxafpenlf = 2 if (raxafpen==2 | raxlfinsvf==2) & inlist(total,1,3) & inxt==1
replace raxafpenlf = 3 if (raxafpen==3 | raxlfinsvf==3) & inlist(total,1,3) & inxt==1
replace raxafpenlf = 5 if (raxafpen==5 | raxlfinsvf==5) & inlist(total,1,3) & inxt==1
replace raxafpenlf = 7 if (raxafpen==7 | raxlfinsvf==7) & inlist(total,1,3) & inxt==1
replace raxafpenlf = -1 if (raxafpen==-1 | raxlfinsvf==-1) & inlist(total,1,3) & inxt==1
replace raxafpenlf = -2 if (raxafpen==-2 | raxlfinsvf==-2) & inlist(total,1,3) & inxt==1

replace raxafpenlf = exg019_1_fimput if inlist(total,2,4) & inxt==1


***other inheritance - financial assets - component 1***
*adjust for cpi*
forvalues y = 2011/2014 {
	replace afnas1_min = ((afnas1_min*100)/c`y'cpindex) if raxyear==`y' & inrange(afnas1_min,0,500000)
	replace afnas1_max = ((afnas1_max*100)/c`y'cpindex) if raxyear==`y' & inrange(afnas1_max,0,2000000)
	replace afnas1_    = ((afnas1_*100)/c`y'cpindex)    if raxyear==`y' & inrange(afnas1_,0,600000)
}
*impute missing values*
charls_eol_impute afnas1_ if inxt==1, entry_var(afnas1_o)
*assign to variables*
replace raxafnas1 = afnas1__i if !mi(afnas1__i) & inxt==1
replace raxafnas1 = .m if raxafnas1==. & inxt==1

replace raxaffnas1 = afnas1__i_f if !mi(afnas1__i_f) & inxt==1

drop afnas1_o afnas1_min afnas1_max afnas1_ afnas1__i afnas1__i_f afnas1__i_neighbor

***other inheritance - financial assets - component 2***
*adjust for cpi*
forvalues y = 2011/2014 {
	replace afnas2_min = ((afnas2_min*100)/c`y'cpindex) if raxyear==`y' & inrange(afnas2_min,0,500000)
	replace afnas2_max = ((afnas2_max*100)/c`y'cpindex) if raxyear==`y' & inrange(afnas2_max,0,2000000)
	replace afnas2_    = ((afnas2_*100)/c`y'cpindex)    if raxyear==`y' & inrange(afnas2_,0,600000)
}
*impute missing values*
charls_eol_impute afnas2_ if inxt==1, entry_var(afnas2_o)
*assign to variables*
replace raxafnas2 = afnas2__i if !mi(afnas2__i) & inxt==1
replace raxafnas2 = .m if raxafnas2==. & inxt==1

replace raxaffnas2 = afnas2__i_f if !mi(afnas2__i_f) & inxt==1

drop afnas2_o afnas2_min afnas2_max afnas2_ afnas2__i afnas2__i_f afnas2__i_neighbor

***other inheritance - financial assets - component 3***
*adjust for cpi*
forvalues y = 2011/2014 {
	replace afnas3_min = ((afnas3_min*100)/c`y'cpindex) if raxyear==`y' & inrange(afnas3_min,0,500000)
	replace afnas3_max = ((afnas3_max*100)/c`y'cpindex) if raxyear==`y' & inrange(afnas3_max,0,2000000)
	replace afnas3_    = ((afnas3_*100)/c`y'cpindex)    if raxyear==`y' & inrange(afnas3_,0,600000)
}
*impute missing values*
charls_eol_impute afnas3_ if inxt==1, entry_var(afnas3_o)
*assign to variables*
replace raxafnas3 = afnas3__i if !mi(afnas3__i) & inxt==1
replace raxafnas3 = .m if raxafnas3==. & inxt==1

replace raxaffnas3 = afnas3__i_f if !mi(afnas3__i_f) & inxt==1

drop afnas3_o afnas3_min afnas3_max afnas3_ afnas3__i afnas3__i_f afnas3__i_neighbor


***ADD ALL 3 FINANCIAL ASSETS' VARIABLES TOGETHER
*Generate total variable
gen raxafnas = raxafnas1 + raxafnas2 + raxafnas3 if inxt==1
replace raxafnas = .m if raxafnas==. & inxt==1
label variable raxafnas "raxafnas: r asset: financial assets inheritance"

gen raxaffnas = .
label variable raxaffnas "raxaffnas: r asset flag: financial assets inheritance"
label values raxaffnas flagasset


replace raxaffnas = 6 if (raxaffnas1==6 | raxaffnas2==6 | raxaffnas3==6) & inxt==1
replace raxaffnas = 1 if (raxaffnas1==1 | raxaffnas2==1 | raxaffnas3==1) & inxt==1
replace raxaffnas = 2 if (raxaffnas1==2 | raxaffnas2==2 | raxaffnas3==2) & inxt==1
replace raxaffnas = 3 if (raxaffnas1==3 | raxaffnas2==3 | raxaffnas3==3) & inxt==1
replace raxaffnas = 5 if (raxaffnas1==5 | raxaffnas2==5 | raxaffnas3==5) & inxt==1
replace raxaffnas = 7 if (raxaffnas1==7 | raxaffnas2==7 | raxaffnas3==7) & inxt==1
replace raxaffnas = -1 if (raxaffnas1==-1 | raxaffnas2==-1 | raxaffnas3==-1) & inxt==1
replace raxaffnas = -2 if (raxaffnas1==-2 | raxaffnas2==-2 | raxaffnas3==-2) & inxt==1


***other inheritance - physical assets - component 4***
*adjust for cpi*
forvalues y = 2011/2014 {
	replace aphas_min = ((aphas_min*100)/c`y'cpindex) if raxyear==`y' & inrange(aphas_min,0,500000)
	replace aphas_max = ((aphas_max*100)/c`y'cpindex) if raxyear==`y' & inrange(aphas_max,0,2000000)
	replace aphas_    = ((aphas_*100)/c`y'cpindex)    if raxyear==`y' & inrange(aphas_,0,600000)
}
*impute missing values*
charls_eol_impute aphas_ if inxt==1, entry_var(aphas_o)
*assign to variables*
replace raxaphas = aphas__i if !mi(aphas__i) & inxt==1
replace raxaphas = .m if raxaphas==. & inxt==1


replace raxafphas = aphas__i_f if !mi(aphas__i_f) & inxt==1

drop aphas_o aphas_min aphas_max aphas_ aphas__i aphas__i_f aphas__i_neighbor


***total inheritance - imputation of total value***
*adjust for cpi*
forvalues y = 2011/2014 {
	replace exg027_min = ((exg027_min*100)/c`y'cpindex) if raxyear==`y' & inrange(exg027_min,0,500000)
	replace exg027_max = ((exg027_max*100)/c`y'cpindex) if raxyear==`y' & inrange(exg027_max,0,2000000)
	replace exg027_    = ((exg027_*100)/c`y'cpindex)    if raxyear==`y' & inrange(exg027_,0,600000)
}
*impute missing values*
charls_eol_impute exg027_ if inxt==1, entry_var(exg027_o)
*assign to variables*
replace exg027_imput = exg027__i if !mi(exg027__i) & inxt==1
replace exg027_imput = .m if exg027_imput==. & inxt==1

replace exg027_fimput = exg027__i_f if !mi(exg027__i_f) & inxt==1

drop exg027_o exg027_min exg027_max exg027_ exg027__i exg027__i_f exg027__i_neighbor


***total non-housing wealth***
gen totnsum = raxapenlf + raxafnas + raxaphas if inxt==1

replace raxatotn = max(totnsum, exg027_imput) if inxt==1 
replace raxatotn = .m if raxatotn==. & inxt==1

***extra flag for sum or imputed total
gen raxaftotns = .
replace raxaftotns = 1 if ((totnsum >= exg027_imput & !mi(totnsum)) | (mi(exg027_imput) & !mi(totnsum))) & inxt==1
replace raxaftotns = 2 if ((totnsum < exg027_imput & !mi(exg027_imput)) | (mi(totnsum) & !mi(exg027_imput))) & inxt==1
replace raxaftotns = .m if raxatotn==.m & inxt==1
label variable raxaftotns "raxaftotns: R asset source flag: total non-housing assets"
label values raxaftotns flagassetsum

replace raxaftotn = 6 if (((raxafpenlf==6 | raxaffnas==6 | raxafphas==6) & raxaftotns==1) | (exg027_fimput==6 & raxaftotns==2)) & inxt==1
replace raxaftotn = 1 if (((raxafpenlf==1 | raxaffnas==1 | raxafphas==1) & raxaftotns==1) | (exg027_fimput==1 & raxaftotns==2)) & inxt==1
replace raxaftotn = 2 if (((raxafpenlf==2 | raxaffnas==2 | raxafphas==2) & raxaftotns==1) | (exg027_fimput==2 & raxaftotns==2)) & inxt==1
replace raxaftotn = 3 if (((raxafpenlf==3 | raxaffnas==3 | raxafphas==3) & raxaftotns==1) | (exg027_fimput==3 & raxaftotns==2)) & inxt==1
replace raxaftotn = 5 if (((raxafpenlf==5 | raxaffnas==5 | raxafphas==5) & raxaftotns==1) | (exg027_fimput==5 & raxaftotns==2)) & inxt==1
replace raxaftotn = 7 if (((raxafpenlf==7 | raxaffnas==7 | raxafphas==7) & raxaftotns==1) | (exg027_fimput==7 & raxaftotns==2)) & inxt==1
replace raxaftotn = -1 if (((raxafpenlf==-1 | raxaffnas==-1 | raxafphas==-1) & raxaftotns==1) | (exg027_fimput==-1 & raxaftotns==2)) & inxt==1
replace raxaftotn = -2 if (((raxafpenlf==-2 | raxaffnas==-2 | raxafphas==-2) & raxaftotns==1) | (exg027_fimput==-2 & raxaftotns==2)) & inxt==1
replace raxaftotn = -2 if (raxafpenlf==-2 | raxaffnas==-2 | raxafphas==-2 | exg027_fimput==-2) & inxt==1

***total wealth*** 
replace raxatotb = raxahous + raxatotn if inxt==1 
replace raxatotb = .m if raxatotb==. & inxt==1
replace raxatotb = raxahous if inlist(raxahous,.i,.z) & inxt==1

replace raxaftotb = 6 if (raxafhous==6 | raxaftotn==6) & inxt==1
replace raxaftotb = 1 if (raxafhous==1 | raxaftotn==1) & inxt==1
replace raxaftotb = 2 if (raxafhous==2 | raxaftotn==2) & inxt==1
replace raxaftotb = 3 if (raxafhous==3 | raxaftotn==3) & inxt==1
replace raxaftotb = 5 if (raxafhous==5 | raxaftotn==5) & inxt==1
replace raxaftotb = 7 if (raxafhous==7 | raxaftotn==7) & inxt==1
replace raxaftotb = -1 if (raxafhous==-1 | raxaftotn==-1) & inxt==1
replace raxaftotb = -2 if (raxafhous==-2 | raxaftotn==-2) & inxt==1
replace raxaftotb = raxafhous if inlist(raxafhous,.i,.z) & inxt==1


***Drop extra intermediate variables
drop total exg019_1_imput exg019_1_fimput exg027_imput exg027_fimput
drop raxapen_pre raxafpen_pre raxapen_oth raxafpen_oth raxapen_ols raxafpen_ols
drop raxafnas1 raxaffnas1 raxafnas2 raxaffnas2 raxafnas3 raxaffnas3
drop penlf maxplf totnsum




******************************************************************************************



***yes or no***
label define yesnofam ///
	0 "0.no" ///
	1 "1.yes"  
	
***child flag***
label define kidflag ///
	1 "1.exit-r level" ///
	2 "2.core-h level" 


	

*set wave number
local wv=2
local pre_wv=1



*****merge with wave 2 harmonized CHARLS data***
local famxt_w2_hcharls h1child h1dchild 
merge 1:1 ID using "$h_charls", keepusing(`famxt_w2_hcharls') nogen

*****merge with wave 2 CHARLS Exit Interview***
local famxt_w2_xt exc001 exc003 exc005 exc006
merge 1:1 ID using "$wave_2_xt", keepusing(`famxt_w2_xt')

drop if _merge==2
drop _merge

**********************************************************************************

***Number of children alive***  
*wave 2 respondent
gen raxchild = .
missing exc001 if inw`wv'xt==1, result(raxchild)
replace raxchild = exc001 if inrange(exc001,0,100)
replace raxchild = h1child if inrange(h1child,0,100) & ralstcore==1 & mi(raxchild) & inw`wv'xt==1
label variable raxchild "raxchild:r # of children alive before R's death"

*flag
gen raxchildf = .
replace raxchildf = 1 if inrange(exc001,0,100)
replace raxchildf = 2 if inrange(h1child,0,100) & !inrange(exc001,0,100) & !mi(h1child) & inw`wv'xt==1
label variable raxchildf "raxchildf: flag # of children alive before R's death"
label values raxchildf kidflag

***Number of children dead***  
*wave 2 respondent
gen raxdchild = .
missing exc003 if inw`wv'xt==1, result(raxdchild)
replace raxdchild = exc003 if inrange(exc003,0,100)
replace raxdchild = h1dchild if inrange(h1dchild,0,100) & ralstcore==1 & mi(raxdchild) & inw`wv'xt==1
label variable raxdchild "raxdchild:r # of children died before R's death"

*flag
gen raxdchildf = .
replace raxdchildf = 1 if inrange(exc003,0,100)
replace raxdchildf = 2 if inrange(h1dchild,0,100) & !inrange(exc003,0,100) & !mi(h1dchild) & inw`wv'xt==1
label variable raxdchildf "raxdchildf: flag # of children died before R's death"
label values raxdchildf kidflag

***Number of grandchildren alive***  
*wave 2 respondent
gen raxgrchild = .
missing exc005 if inw`wv'xt==1, result(raxgrchild)
replace raxgrchild = exc005 if inrange(exc005,0,100)
label variable raxgrchild "raxgrchild:r # of grandchildren alive before R's death"


***Number of great-grandchildren alive***  
*wave 2 respondent
gen raxggrchild = .
missing exc006 if inw`wv'xt==1, result(raxggrchild)
replace raxggrchild = exc006 if inrange(exc006,0,100)
label variable raxggrchild "raxggrchild:r # of great-grandchildren alive before R's death"


**********************************************************************************

***drop Harmonized CHARLS wave 2 variables***
drop `famxt_w2_hcharls'

****drop CHARLS EOL Exit Interview variables***
drop `famxt_w2_xt'


******************************************************************************************



***yes or no***
label define yesnoemp ///
	0 "0.no" ///
	1 "1.yes" 
	

***yes or no***
label define yesnoret ///
	0 "0.no" ///
	1 "1.yes" ///
	.w ".w:working until death"

	

*set wave number
local wv=2
local pre_wv=1



****merge with wave 2 harmonized CHARLS data***
local employxt_w2_hcharls r`pre_wv'work r`pre_wv'fret_c 
merge 1:1 ID using "$h_charls", keepusing(`employxt_w2_hcharls') nogen

*****merge with wave 2 CHARLS Exit Interview***
local employxt_w2_xt exf001 exf001_1 exf001_2 exf004 zf1 zf15 
merge 1:1 ID using "$wave_2_xt", keepusing(`employxt_w2_xt')

drop if _merge==2
drop _merge

**********************************************************************************

***Working for pay at death***
*wave 2 respondent
gen raxwork = .
missing exf001 r`pre_wv'work if inw`wv'xt==1, result(raxwork)
replace raxwork = 0 if inlist(exf001,1,3) | (r`pre_wv'work==0 & inw`wv'xt==1)
replace raxwork = 1 if exf001==2
label variable raxwork "raxwork: r worked up until time of death"
label values raxwork yesnoemp

***Year stopped working*** 
*wave 2 respondent
gen raxjlasty_c = .
missing exf001 exf001_1 r`pre_wv'work raxyear if inw`wv'xt==1, result(raxjlasty_c)
replace raxjlasty_c = .x if exf001==3 | (r`pre_wv'work==0 & inw`wv'xt==1)
replace raxjlasty_c = raxyear if inrange(raxyear,1900,2020) & exf001==2
replace raxjlasty_c = exf001_1 if !mi(exf001_1) //exf001==1 & 
label variable raxjlasty_c "raxjlasty_c: r year last worked" 

***Month stopped working***  
*wave 2 respondent
gen raxjlastm_c = .
missing exf001 exf001_2 r`pre_wv'work raxmonth if inw`wv'xt==1, result(raxjlastm_c)
replace raxjlastm_c = .m if exf001_2==0
replace raxjlastm_c = .x if exf001==3 | (r`pre_wv'work==0 & inw`wv'xt==1)
replace raxjlastm_c = raxmonth if inrange(raxmonth,1,12) & exf001==2
replace raxjlastm_c = exf001_2 if !mi(exf001_2) & inrange(exf001_2,1,12) & exf001_2!=0 //exf001==1 & 
replace raxjlastm_c = .m if !mi(exf001_2) & exf001_2==0 & exf001_2!=0 //exf001==1 & 
label variable raxjlastm_c "raxjlastm_c: r month last worked" 

***Whether retired before death***
*wave 2 respondent
gen raxfret_c = .
missing exf004 r`pre_wv'fret_c if inw`wv'xt==1, result(raxfret_c)
replace raxfret_c = .w if raxwork==1 & inw`wv'xt==1 //added & ...
replace raxfret_c = 0 if exf004==2 //no formal retirement
replace raxfret_c = 0 if exf001==3 & r`pre_wv'fret_c==0 & inw`wv'xt==1 //not working and no formal ret
replace raxfret_c = 0 if r`pre_wv'work==0 & inlist(r`pre_wv'fret_c,0,.w) & inw`wv'xt==1 //not working/never worked and no formal ret
replace raxfret_c = 0 if exf001==1 & zf1==1 & raxwork==0 & r`pre_wv'fret_c==0 & inw`wv'xt==1 //agricultural work only and no formal ret
replace raxfret_c = 1 if exf004==1 | (r`pre_wv'fret_c==1 & inw`wv'xt==1)
label variable raxfret_c "raxfret_c: r retired before death"
label values raxfret_c yesnoret


**********************************************************************************

***drop Harmonized CHARLS wave 2 variables***
drop `employxt_w2_hcharls'

****drop CHARLS EOL Exit Interview variables***
drop `employxt_w2_xt'


******************************************************************************************


	
***yes or no***
label define yesnocare ///
	0 "0.no" ///
	1 "1.yes" ///
	.t ".t:could not do" ///
	.j ".j:did not do" ///
	.i ".i:invalid age" ///
	.h ".h:no help received" ///
	.l ".l:not due to health/memory" 
	



	

*set wave number
local wv=2
local pre_wv=1



****merge with wave 2 harmonized CHARLS data***
local carext_w2_hcharls rabyear rabmonth
merge 1:1 ID using "$h_charls", keepusing(`carext_w2_hcharls') nogen


*****merge with wave 2 CHARLS Exit Interview***
local carext_w2_xt exdb010_w2_1 exdb010_w2_2_1 exdb010_w2_2_2 exdb010_w2_2_3 exdb010_w2_2_4 ///
									 exdb011_w2_1 exdb011_w2_2_1 exdb011_w2_2_2 exdb011_w2_2_3 exdb011_w2_2_4 ///
									 exdb012_w2_1 exdb012_w2_2_1 exdb012_w2_2_2 exdb012_w2_2_3 exdb012_w2_2_4 ///
									 exdb013_w2_1 exdb013_w2_2_1 exdb013_w2_2_2 exdb013_w2_2_3 exdb013_w2_2_4 ///
									 exdb014_w2_1 exdb014_w2_2_1 exdb014_w2_2_2 exdb014_w2_2_3 exdb014_w2_2_4 ///
									 exdb017_w2_1 exdb017_w2_2 exdb017_w2_3_1 exdb017_w2_3_2 exdb017_w2_3_3 exdb017_w2_3_4 ///
									 exdb018_w2_1 exdb018_w2_2 exdb018_w2_3_1 exdb018_w2_3_2 exdb018_w2_3_3 exdb018_w2_3_4 ///							 
									 exdb035_w2_1 exdb035_w2_2 exdb035_w2_3_1 exdb035_w2_3_2 exdb035_w2_3_3 exdb035_w2_3_4 ///
									 exdb020_w2_1 exdb020_w2_2 exdb020_w2_3_1 exdb020_w2_3_2 exdb020_w2_3_3 exdb020_w2_3_4 ///
									 exdb019_w2_1 exdb019_w2_2 exdb019_w2_3_1 exdb019_w2_3_2 exdb019_w2_3_3 exdb019_w2_3_4 ///
									 exdb029s1 exdb029s2 exdb029s3 exdb029s4 exdb029s5 exdb029s6 exdb029s7 ///
									 exdb022_w2_1_1_s* exdb022_w2_1_1_s1* exdb022_w2_1_1_s2* exdb022_w2_1_1_s3* ///
									 exdb022_w2_1_1_s4* exdb022_w2_1_1_s5* exdb022_w2_1_1_s6* ///
									 exdb022_w2_1_2_s* exdb022_w2_1_2_s1* exdb022_w2_1_2_s2* exdb022_w2_1_2_s3* ///
									 exdb022_w2_1_2_s4* exdb022_w2_1_2_s5* exdb022_w2_1_2_s6* ///
									 exdb022_w2_1_3_s* exdb022_w2_1_3_s1* exdb022_w2_1_3_s2* exdb022_w2_1_3_s3* ///
									 exdb022_w2_1_3_s4* exdb022_w2_1_3_s5* exdb022_w2_1_3_s6* ///
									 exdb022_w2_5_1_s* exdb022_w2_5_1_s1* exdb022_w2_5_1_s2* exdb022_w2_5_1_s3* ///
									 exdb022_w2_5_1_s4* exdb022_w2_5_1_s5* exdb022_w2_5_1_s6* ///
									 exdb022_w2_5_2_s* exdb022_w2_5_2_s1* exdb022_w2_5_2_s2* exdb022_w2_5_2_s3* ///
									 exdb022_w2_5_2_s4* exdb022_w2_5_2_s5* exdb022_w2_5_2_s6* ///
									 exdb022_w2_5_3_s* exdb022_w2_5_3_s1* exdb022_w2_5_3_s2* exdb022_w2_5_3_s3* ///
									 exdb022_w2_5_3_s4* exdb022_w2_5_3_s5* exdb022_w2_5_3_s6* ///
									 exdb022_w2_5_4_s* exdb022_w2_5_4_s1* exdb022_w2_5_4_s2* exdb022_w2_5_4_s3* ///
									 exdb022_w2_5_4_s4* exdb022_w2_5_4_s5* exdb022_w2_5_4_s6 ///
									 exdb022_w2_9_1_s* exdb022_w2_9_1_s1* exdb022_w2_9_1_s2* exdb022_w2_9_1_s3* ///
									 exdb022_w2_9_1_s4* exdb022_w2_9_1_s5* exdb022_w2_9_1_s6* ///
									 exdb022_w2_9_2_s* exdb022_w2_9_2_s1* exdb022_w2_9_2_s2* exdb022_w2_9_2_s3* ///
									 exdb022_w2_9_2_s4* exdb022_w2_9_2_s5* exdb022_w2_9_2_s6*
merge 1:1 ID using "$wave_2_xt", keepusing(`carext_w2_xt')

drop if _merge==2
drop _merge


**********************************************************************************

**************************
**********ADLs************
**************************            
																				
*Temporary dmonths variable																			
gen dmonths = .
replace dmonths = (raxyear - rabyear)*12
replace dmonths = dmonths + (raxmonth - rabmonth) if !mi(raxmonth) & !mi(rabmonth)
************Dressing***********

*wave 2 respondent
gen raxdresshlp = .
missing exdb010_w2_1 if inw`wv'xt==1, result(raxdresshlp)
replace raxdresshlp = .t if exdb010_w2_1==3
replace raxdresshlp = .j if exdb010_w2_1==4
replace raxdresshlp = 0 if exdb010_w2_1==2
replace raxdresshlp = 1 if exdb010_w2_1==1
label variable raxdresshlp "raxdresshlp: someone helped r dress final 3 months"
label values raxdresshlp yesnocare

gen raxdressage = .
missing exdb010_w2_2_1 exdb010_w2_2_2 exdb010_w2_2_3 exdb010_w2_2_4 rabyear radage  if inw`wv'xt==1, result(raxdressage)
replace raxdressage = .h if exdb010_w2_1==2 
replace raxdressage = exdb010_w2_2_4 - rabyear if !mi(exdb010_w2_2_4) & !mi(rabyear) & inlist(exdb010_w2_1,1,3,4) 
replace raxdressage = radage - exdb010_w2_2_2  if !mi(exdb010_w2_2_2) & !mi(radage) & inlist(exdb010_w2_1,1,3,4)
replace raxdressage = floor((dmonths - exdb010_w2_2_1)/12) if inrange(exdb010_w2_2_1,0,20) & !mi(dmonths) 
replace raxdressage = exdb010_w2_2_3 if !mi(exdb010_w2_2_3) & inlist(exdb010_w2_1,1,3,4) 
replace raxdressage = radage if raxdressage==(radage+1) & rabmonth > raxmonth & !mi(rabmonth) & !mi(raxmonth) & inw`wv'xt==1
replace raxdressage = .i if ((raxdressage > radage) | (raxdressage < 0)) & !mi(raxdressage) & !mi(radage) & inw`wv'xt==1 
label variable raxdressage "raxdressage: age r began to need help dressing"

*wave2 respondent began needing help dressing within final year
gen raxdressb1y = .
missing raxdressage radage raxyear exdb010_w2_2_1 exdb010_w2_2_2 exdb010_w2_2_3 exdb010_w2_2_4 if inw`wv'xt==1, result(raxdressb1y)
replace raxdressb1y = .h if raxdresshlp==0 & inw`wv'xt==1
replace raxdressb1y = 0 if inrange(exdb010_w2_2_1,13,20) | ///
													inrange(exdb010_w2_2_2,2,7) | ///
													(((radage - exdb010_w2_2_3) > 1) & !mi(radage) & inrange(exdb010_w2_2_3,55,71)) | ///
													(((raxyear - exdb010_w2_2_4) > 1) & !mi(raxyear) & inrange(exdb010_w2_2_4,1989,2013)) 
replace raxdressb1y = 1 if inrange(exdb010_w2_2_1,0,12) | ///
													inrange(exdb010_w2_2_2,0,1) | ///
													((((radage - exdb010_w2_2_3) == 0) | ((radage - exdb010_w2_2_3) == 1)) & !mi(radage) & inrange(exdb010_w2_2_3,55,71)) | ///
													((((raxyear - exdb010_w2_2_4) == 0) | ((raxyear - exdb010_w2_2_4) == 1)) & !mi(raxyear) & inrange(exdb010_w2_2_4,1989,2013))
replace raxdressb1y = .i if raxdressage==.i & inw`wv'xt==1 
label variable raxdressb1y "raxdressb1y: r final help with dressing started within year"
label values raxdressb1y yesnocare


************Bathing***********

*wave 2 respondent
gen raxbathehlp = .
missing exdb011_w2_1 if inw`wv'xt==1, result(raxbathehlp)
replace raxbathehlp = .t if exdb011_w2_1==3
replace raxbathehlp = .j if exdb011_w2_1==4
replace raxbathehlp = 0 if exdb011_w2_1==2
replace raxbathehlp = 1 if exdb011_w2_1==1
label variable raxbathehlp "raxbathehlp: someone helped r bathe final 3 months"
label values raxbathehlp yesnocare

gen raxbatheage = .
missing exdb011_w2_2_1 exdb011_w2_2_2 exdb011_w2_2_3 exdb011_w2_2_4 rabyear radage  if inw`wv'xt==1, result(raxbatheage)
replace raxbatheage = .h if exdb011_w2_1==2
replace raxbatheage = exdb011_w2_2_4 - rabyear if !mi(exdb011_w2_2_4) & !mi(rabyear) & inlist(exdb011_w2_1,1,3,4) 
replace raxbatheage = radage - exdb011_w2_2_2  if !mi(exdb011_w2_2_2) & !mi(radage) & inlist(exdb011_w2_1,1,3,4)
replace raxbatheage = floor((dmonths - exdb011_w2_2_1)/12) if inrange(exdb011_w2_2_1,0,20) & !mi(dmonths)
replace raxbatheage = exdb011_w2_2_3 if !mi(exdb011_w2_2_3) & inlist(exdb011_w2_1,1,3,4)
replace raxbatheage = radage if raxbatheage==(radage+1) & rabmonth > raxmonth & !mi(rabmonth) & !mi(raxmonth) & inw`wv'xt==1
replace raxbatheage = .i if ((raxbatheage > radage) | (raxbatheage < 0)) & !mi(raxbatheage) & !mi(radage) & inw`wv'xt==1
label variable raxbatheage "raxbatheage: age r began to need help bathing"

*wave2 respondent began needing help bathing within final year
gen raxbatheb1y = .
missing raxbatheage radage raxyear exdb011_w2_2_1 exdb011_w2_2_2 exdb011_w2_2_3 exdb011_w2_2_4 if inw`wv'xt==1, result(raxbatheb1y)
replace raxbatheb1y = .h if raxbathehlp==0 & inw`wv'xt==1
replace raxbatheb1y = 0 if inrange(exdb011_w2_2_1,13,20) | ///
													inrange(exdb011_w2_2_2,2,15) | ///
													(((radage - exdb011_w2_2_3) > 1) & !mi(radage) & inrange(exdb011_w2_2_3,6,83)) | ///
													(((raxyear - exdb011_w2_2_4) > 1) & !mi(raxyear) & inrange(exdb011_w2_2_4,1989,2013)) 
replace raxbatheb1y = 1 if inrange(exdb011_w2_2_1,0,12) | ///
													inrange(exdb011_w2_2_2,0,1) | ///
													((((radage - exdb011_w2_2_3) == 0) | ((radage - exdb011_w2_2_3) == 1)) & !mi(radage) & inrange(exdb011_w2_2_3,6,83)) | ///
													((((raxyear - exdb011_w2_2_4) == 0) | ((raxyear - exdb011_w2_2_4) == 1)) & !mi(raxyear) & inrange(exdb011_w2_2_4,1989,2013))
replace raxbatheb1y = .i if raxbatheage==.i & inw`wv'xt==1
label variable raxbatheb1y "raxbatheb1y: r final help with bathing started within year"
label values raxbatheb1y yesnocare

************Eating***********

*wave 2 respondent
gen raxeathlp = .
missing exdb012_w2_1 if inw`wv'xt==1, result(raxeathlp)
replace raxeathlp = .t if exdb012_w2_1==3
replace raxeathlp = .j if exdb012_w2_1==4
replace raxeathlp = 0 if exdb012_w2_1==2
replace raxeathlp = 1 if exdb012_w2_1==1
label variable raxeathlp "raxeathlp: someone helped r eat final 3 months"
label values raxeathlp yesnocare

gen raxeatage = .
missing exdb012_w2_2_1 exdb012_w2_2_2 exdb012_w2_2_3 exdb012_w2_2_4 rabyear radage  if inw`wv'xt==1, result(raxeatage)
replace raxeatage = .h if exdb012_w2_1==2
replace raxeatage = exdb012_w2_2_4 - rabyear if !mi(exdb012_w2_2_4) & !mi(rabyear) & inlist(exdb012_w2_1,1,3,4)  
replace raxeatage = radage - exdb012_w2_2_2  if !mi(exdb012_w2_2_2) & !mi(radage) & inlist(exdb012_w2_1,1,3,4)
replace raxeatage = floor((dmonths - exdb012_w2_2_1)/12) if inrange(exdb012_w2_2_1,0,20) & !mi(dmonths)
replace raxeatage = exdb012_w2_2_3 if !mi(exdb012_w2_2_3) & inlist(exdb012_w2_1,1,3,4)
replace raxeatage = radage if raxeatage==(radage+1) & rabmonth > raxmonth & !mi(rabmonth) & !mi(raxmonth) & inw`wv'xt==1
replace raxeatage = .i if ((raxeatage > radage) | (raxeatage < 0)) & !mi(raxeatage) & !mi(radage) & inw`wv'xt==1
label variable raxeatage "raxeatage: age r began to need help eating"

*wave2 respondent began needing help eating within final year
gen raxeatb1y = .
missing raxeatage radage raxyear exdb012_w2_2_1 exdb012_w2_2_2 exdb012_w2_2_3 exdb012_w2_2_4 if inw`wv'xt==1, result(raxeatb1y)
replace raxeatb1y = .h if raxeathlp==0 & inw`wv'xt==1
replace raxeatb1y = 0 if inrange(exdb012_w2_2_1,13,20) | ///
													inrange(exdb012_w2_2_2,2,4) | ///
													(((radage - exdb012_w2_2_3) > 1) & !mi(radage) & inrange(exdb012_w2_2_3,60,71)) | ///
													(((raxyear - exdb012_w2_2_4) > 1) & !mi(raxyear) & inrange(exdb012_w2_2_4,1989,2013)) 
replace raxeatb1y = 1 if inrange(exdb012_w2_2_1,0,12) | ///
													inrange(exdb012_w2_2_2,0,1) | ///
													((((radage - exdb012_w2_2_3) == 0) | ((radage - exdb012_w2_2_3) == 1)) & !mi(radage) & inrange(exdb012_w2_2_3,60,71)) | ///
													((((raxyear - exdb012_w2_2_4) == 0) | ((raxyear - exdb012_w2_2_4) == 1)) & !mi(raxyear) & inrange(exdb012_w2_2_4,1989,2013))
replace raxeatb1y = .i if raxeatage==.i & inw`wv'xt==1
label variable raxeatb1y "raxeatb1y: r final help with eating started within year"
label values raxeatb1y yesnocare

************Getting in and out of bed***********

*wave 2 respondent
gen raxbedhlp = .
missing exdb013_w2_1 if inw`wv'xt==1, result(raxbedhlp)
replace raxbedhlp = .t if exdb013_w2_1==3
replace raxbedhlp = .j if exdb013_w2_1==4
replace raxbedhlp = 0 if exdb013_w2_1==2
replace raxbedhlp = 1 if exdb013_w2_1==1
label variable raxbedhlp "raxbedhlp: someone helped r get in and out of bed final 3 months"
label values raxbedhlp yesnocare

gen raxbedage = .
missing exdb013_w2_2_1 exdb013_w2_2_2 exdb013_w2_2_3 exdb013_w2_2_4 rabyear radage  if inw`wv'xt==1, result(raxbedage)
replace raxbedage = .h if exdb013_w2_1==2
replace raxbedage = exdb013_w2_2_4 - rabyear if !mi(exdb013_w2_2_4) & !mi(rabyear) & inlist(exdb013_w2_1,1,3,4)
replace raxbedage = radage - exdb013_w2_2_2  if !mi(exdb013_w2_2_2) & !mi(radage) & inlist(exdb013_w2_1,1,3,4)
replace raxbedage = floor((dmonths - exdb013_w2_2_1)/12) if inrange(exdb013_w2_2_1,0,20) & !mi(dmonths)
replace raxbedage = exdb013_w2_2_3 if !mi(exdb013_w2_2_3) & inlist(exdb013_w2_1,1,3,4)
replace raxbedage = radage if raxbedage==(radage+1) & rabmonth > raxmonth & !mi(rabmonth) & !mi(raxmonth) & inw`wv'xt==1
replace raxbedage = .i if ((raxbedage > radage) | (raxbedage < 0)) & !mi(raxbedage) & !mi(radage) & inw`wv'xt==1
label variable raxbedage "raxbedage: age r began to need help getting in and out of bed"

*wave2 respondent began needing help getting in and out of bed within final year
gen raxbedb1y = .
missing raxbedage radage raxyear exdb013_w2_2_1 exdb013_w2_2_2 exdb013_w2_2_3 exdb013_w2_2_4 if inw`wv'xt==1, result(raxbedb1y)
replace raxbedb1y = .h if raxbedhlp==0 & inw`wv'xt==1
replace raxbedb1y = 0 if inrange(exdb013_w2_2_1,13,20) | ///
													inrange(exdb013_w2_2_2,2,7) | ///
													(((radage - exdb013_w2_2_3) > 1) & !mi(radage) & inrange(exdb013_w2_2_3,49,71)) | ///
													(((raxyear - exdb013_w2_2_4) > 1) & !mi(raxyear) & inrange(exdb013_w2_2_4,1989,2013)) 
replace raxbedb1y = 1 if inrange(exdb013_w2_2_1,0,12) | ///
													inrange(exdb013_w2_2_2,0,1) | ///
													((((radage - exdb013_w2_2_3) == 0) | ((radage - exdb013_w2_2_3) == 1)) & !mi(radage) & inrange(exdb013_w2_2_3,49,71)) | ///
													((((raxyear - exdb013_w2_2_4) == 0) | ((raxyear - exdb013_w2_2_4) == 1)) & !mi(raxyear) & inrange(exdb013_w2_2_4,1989,2013))
replace raxbedb1y = .i if raxbedage==.i & inw`wv'xt==1
label variable raxbedb1y "raxbedb1y: r final help with getting in/out bed started within year"
label values raxbedb1y yesnocare

************Use the toilet***********

*wave 2 respondent
gen raxtoilethlp = .
missing exdb014_w2_1 if inw`wv'xt==1, result(raxtoilethlp)
replace raxtoilethlp = .t if exdb014_w2_1==3
replace raxtoilethlp = .j if exdb014_w2_1==4
replace raxtoilethlp = 0 if exdb014_w2_1==2
replace raxtoilethlp = 1 if exdb014_w2_1==1
label variable raxtoilethlp "raxtoilethlp: someone helped r use the toilet final 3 months"
label values raxtoilethlp yesnocare

gen raxtoiletage = .
missing exdb014_w2_2_1 exdb014_w2_2_2 exdb014_w2_2_3 exdb014_w2_2_4 rabyear radage  if inw`wv'xt==1, result(raxtoiletage)
replace raxtoiletage = .h if exdb014_w2_1==2
replace raxtoiletage = exdb014_w2_2_4 - rabyear if !mi(exdb014_w2_2_4) & !mi(rabyear) & inlist(exdb014_w2_1,1,3,4)
replace raxtoiletage = radage - exdb014_w2_2_2  if !mi(exdb014_w2_2_2) & !mi(radage) & inlist(exdb014_w2_1,1,3,4)
replace raxtoiletage = floor((dmonths - exdb014_w2_2_1)/12) if inrange(exdb014_w2_2_1,0,20) & !mi(dmonths)
replace raxtoiletage = exdb014_w2_2_3 if !mi(exdb014_w2_2_3) & inlist(exdb014_w2_1,1,3,4) 
replace raxtoiletage = radage if raxtoiletage==(radage+1) & rabmonth > raxmonth & !mi(rabmonth) & !mi(raxmonth) & inw`wv'xt==1
replace raxtoiletage = .i if ((raxtoiletage > radage) | (raxtoiletage < 0)) & !mi(raxtoiletage) & !mi(radage) & inw`wv'xt==1
label variable raxtoiletage "raxtoiletage: age r began to need help using the toilet"

*wave2 respondent began needing help using the toilet within final year
gen raxtoiletb1y = .
missing raxtoiletage radage raxyear exdb014_w2_2_1 exdb014_w2_2_2 exdb014_w2_2_3 exdb014_w2_2_4 if inw`wv'xt==1, result(raxtoiletb1y)
replace raxtoiletb1y = .h if raxtoilethlp==0 & inw`wv'xt==1
replace raxtoiletb1y = 0 if inrange(exdb014_w2_2_1,14,20) | ///
													inrange(exdb014_w2_2_2,2,7) | ///
													(((radage - exdb014_w2_2_3) > 1) & !mi(radage) & inrange(exdb014_w2_2_3,49,71)) | ///
													(((raxyear - exdb014_w2_2_4) > 1) & !mi(raxyear) & inrange(exdb014_w2_2_4,1989,2013)) 
replace raxtoiletb1y = 1 if inrange(exdb014_w2_2_1,0,12) | ///
													inrange(exdb014_w2_2_2,0,1) | ///
													((((radage - exdb014_w2_2_3) == 0) | ((radage - exdb014_w2_2_3) == 1)) & !mi(radage) & inrange(exdb014_w2_2_3,49,71)) | ///
													((((raxyear - exdb014_w2_2_4) == 0) | ((raxyear - exdb014_w2_2_4) == 1)) & !mi(raxyear) & inrange(exdb014_w2_2_4,1989,2013))
replace raxtoiletb1y = .i if raxtoiletage==.i & inw`wv'xt==1
label variable raxtoiletb1y "raxtoiletb1y: r final help with using the toilet started within year"
label values raxtoiletb1y yesnocare


***began needing help with any adl activities within final year***
*wave 2 respondent began needing help with adl activities within final year
gen raxracareb = .
missing raxdressb1y raxbatheb1y raxeatb1y raxbedb1y raxtoiletb1y if inw`wv'xt==1, result(raxracareb) wave(`wv')
replace raxracareb = .h if (raxdressb1y==.h & raxbatheb1y==.h & raxeatb1y==.h & raxbedb1y==.h & raxtoiletb1y==.h) & inw`wv'xt==1
replace raxracareb = 0 if (raxdressb1y==0 | raxbatheb1y==0 | raxeatb1y==0 | raxbedb1y==0 | raxtoiletb1y==0) & inw`wv'xt==1
replace raxracareb = 1 if (raxdressb1y==1 | raxbatheb1y==1 | raxeatb1y==1 | raxbedb1y==1 | raxtoiletb1y==1) & inw`wv'xt==1
replace raxracareb = .i if (raxdressb1y==.i | raxbatheb1y==.i | raxeatb1y==.i | raxbedb1y==.i | raxtoiletb1y==.i) & inw`wv'xt==1
label variable raxracareb "raxracareb: r final help with any adl started within year"
label values raxracareb yesnocare


**********Whether anyone helped with any of the ADLs**********
egen adlsum = rowtotal(exdb022_w2_1_1_s1 - exdb022_w2_1_1_s66),m

gen raxracany = . 
replace raxracany = .m if (raxdresshlp==.m | raxbathehlp==.m | raxeathlp==.m | raxbedhlp==.m | raxtoilethlp==.m) & inw`wv'xt==1
replace raxracany = 0 if (raxdresshlp==0 | raxbathehlp==0 | raxeathlp==0 | raxbedhlp==0 | raxtoilethlp==0) & inw`wv'xt==1
replace raxracany = 1 if (raxdresshlp==1 | raxbathehlp==1 | raxeathlp==1 | raxbedhlp==1 | raxtoilethlp==1) & inw`wv'xt==1
replace raxracany = 1 if inrange(adlsum,1,300) & inw`wv'xt==1
label variable raxracany "raxracany: r received any care for ADLs"
label values raxracany yesnocare

drop adlsum



**************************
**********IADLs***********    
**************************

************Preparing a hot meal***********
*wave 2 respondent
gen raxmealhlp = .
missing exdb017_w2_1 if inw`wv'xt==1, result(raxmealhlp)
replace raxmealhlp = .t if exdb017_w2_1==3
replace raxmealhlp = .j if exdb017_w2_1==4
replace raxmealhlp = 0 if exdb017_w2_1==2
replace raxmealhlp = 1 if exdb017_w2_1==1
label variable raxmealhlp "raxmealhlp: someone helped r prepare a hot meal final 3 months"
label values raxmealhlp yesnocare

gen raxmealage = .
missing exdb017_w2_2 exdb017_w2_3_1 exdb017_w2_3_2 exdb017_w2_3_3 exdb017_w2_3_4 rabyear radage  if inw`wv'xt==1, result(raxmealage)
replace raxmealage = .h if exdb017_w2_1==2
replace raxmealage = .l if exdb017_w2_2==2
replace raxmealage = exdb017_w2_3_4 - rabyear if !mi(exdb017_w2_3_4) & !mi(rabyear) & (exdb017_w2_1==1 | (inlist(exdb017_w2_1,3,4) & exdb017_w2_2==1)) 
replace raxmealage = radage - exdb017_w2_3_2  if !mi(exdb017_w2_3_2) & !mi(radage) & (exdb017_w2_1==1 | (inlist(exdb017_w2_1,3,4) & exdb017_w2_2==1))
replace raxmealage = floor((dmonths - exdb017_w2_3_1)/12) if inrange(exdb017_w2_3_1,0,25) & !mi(dmonths) & (exdb017_w2_1==1 | (inlist(exdb017_w2_1,3,4) & exdb017_w2_2==1)) 
replace raxmealage = exdb017_w2_3_3 if !mi(exdb017_w2_3_3) & (exdb017_w2_1==1 | (inlist(exdb017_w2_1,3,4) & exdb017_w2_2==1))
replace raxmealage = radage if raxmealage==(radage+1) & rabmonth > raxmonth & !mi(rabmonth) & !mi(raxmonth) & inw`wv'xt==1
replace raxmealage = .i if ((raxmealage > radage) | (raxmealage < 0)) & !mi(raxmealage) & !mi(radage) & inw`wv'xt==1 
label variable raxmealage "raxmealage: age r began to need help preparing a hot meal"

*wave2 respondent began needing help preparing a hot meal within final year
gen raxmealb1y = .
missing raxmealage radage raxyear exdb017_w2_3_1 exdb017_w2_3_2 exdb017_w2_3_3 exdb017_w2_3_4 if inw`wv'xt==1, result(raxmealb1y)
replace raxmealb1y = .h if raxmealhlp==0 & inw`wv'xt==1
replace raxmealb1y = .l if exdb017_w2_2==2
replace raxmealb1y = 0 if inrange(exdb017_w2_3_1,13,25) | ///
													inrange(exdb017_w2_3_2,2,75) | ///
													(((radage - exdb017_w2_3_3) > 1) & !mi(radage) & inrange(exdb017_w2_3_3,30,89)) | ///
													(((raxyear - exdb017_w2_3_4) > 1) & !mi(raxyear) & inrange(exdb017_w2_3_4,1963,2013)) 
replace raxmealb1y = 1 if inrange(exdb017_w2_3_1,0,12) | ///
													inrange(exdb017_w2_3_2,0,1) | ///
													((((radage - exdb017_w2_3_3) == 0) | ((radage - exdb017_w2_3_3) == 1)) & !mi(radage) & inrange(exdb017_w2_3_3,30,89)) | ///
													((((raxyear - exdb017_w2_3_4) == 0) | ((raxyear - exdb017_w2_3_4) == 1)) & !mi(raxyear) & inrange(exdb017_w2_3_4,1963,2013))
replace raxmealb1y = .i if raxmealage==.i & inw`wv'xt==1
label variable raxmealb1y "raxmealb1y: r final help with preparing a hot meal started within year"
label values raxmealb1y yesnocare


************Shopping for groceries***********
*wave 2 respondent
gen raxshophlp = .
missing exdb018_w2_1 if inw`wv'xt==1, result(raxshophlp)
replace raxshophlp = .t if exdb018_w2_1==3
replace raxshophlp = .j if exdb018_w2_1==4
replace raxshophlp = 0 if exdb018_w2_1==2
replace raxshophlp = 1 if exdb018_w2_1==1
label variable raxshophlp "raxshophlp: someone helped r grocery shopping final 3 months"
label values raxshophlp yesnocare

gen raxshopage = .
missing exdb018_w2_2 exdb018_w2_3_1 exdb018_w2_3_2 exdb018_w2_3_3 exdb018_w2_3_4 rabyear radage  if inw`wv'xt==1, result(raxshopage)
replace raxshopage = .h if exdb018_w2_1==2
replace raxshopage = .l if exdb018_w2_2==2
replace raxshopage = exdb018_w2_3_4 - rabyear if !mi(exdb018_w2_3_4) & !mi(rabyear) & (exdb018_w2_1==1 | (inlist(exdb018_w2_1,3,4) & exdb018_w2_2==1))
replace raxshopage = radage - exdb018_w2_3_2  if !mi(exdb018_w2_3_2) & !mi(radage) & (exdb018_w2_1==1 | (inlist(exdb018_w2_1,3,4) & exdb018_w2_2==1))
replace raxshopage = floor((dmonths - exdb018_w2_3_1)/12) if inrange(exdb018_w2_3_1,0,22) & !mi(dmonths) & (exdb018_w2_1==1 | (inlist(exdb018_w2_1,3,4) & exdb018_w2_2==1)) 
replace raxshopage = exdb018_w2_3_3 if !mi(exdb018_w2_3_3) & (exdb018_w2_1==1 | (inlist(exdb018_w2_1,3,4) & exdb018_w2_2==1))
replace raxshopage = radage if raxshopage==(radage+1) & rabmonth > raxmonth & !mi(rabmonth) & !mi(raxmonth) & inw`wv'xt==1
replace raxshopage = .i if ((raxshopage > radage) | (raxshopage < 0)) & !mi(raxshopage) & !mi(radage) & inw`wv'xt==1 
label variable raxshopage "raxshopage: age r began to need help grocery shopping"

*wave2 respondent began needing help grocery shopping within final year
gen raxshopb1y = .
missing raxshopage radage raxyear exdb018_w2_3_1 exdb018_w2_3_2 exdb018_w2_3_3 exdb018_w2_3_4 if inw`wv'xt==1, result(raxshopb1y)
replace raxshopb1y = .h if raxshophlp==0 & inw`wv'xt==1
replace raxshopb1y = .l if exdb018_w2_2==2
replace raxshopb1y = 0 if inrange(exdb018_w2_3_1,13,22) | ///
													inrange(exdb018_w2_3_2,2,20) | ///
													(((radage - exdb018_w2_3_3) > 1) & !mi(radage) & inrange(exdb018_w2_3_3,40,89)) | ///
													(((raxyear - exdb018_w2_3_4) > 1) & !mi(raxyear) & inrange(exdb018_w2_3_4,1974,2013)) 
replace raxshopb1y = 1 if inrange(exdb018_w2_3_1,0,12) | ///
													inrange(exdb018_w2_3_2,0,1) | ///
													((((radage - exdb018_w2_3_3) == 0) | ((radage - exdb018_w2_3_3) == 1)) & !mi(radage) & inrange(exdb018_w2_3_3,40,89)) | ///
													((((raxyear - exdb018_w2_3_4) == 0) | ((raxyear - exdb018_w2_3_4) == 1)) & !mi(raxyear) & inrange(exdb018_w2_3_4,1974,2013))
replace raxshopb1y = .i if raxshopage==.i & inw`wv'xt==1
label variable raxshopb1y "raxshopb1y: r final help with grocery shopping started within year"
label values raxshopb1y yesnocare


************Using the phone***********
*wave 2 respondent
gen raxphonehlp = .
missing exdb035_w2_1 if inw`wv'xt==1, result(raxphonehlp)
replace raxphonehlp = .t if exdb035_w2_1==3
replace raxphonehlp = .j if exdb035_w2_1==4
replace raxphonehlp = 0 if exdb035_w2_1==2
replace raxphonehlp = 1 if exdb035_w2_1==1
label variable raxphonehlp "raxphonehlp: someone helped r using the phone final 3 months"
label values raxphonehlp yesnocare

gen raxphoneage = .
missing exdb035_w2_2 exdb035_w2_3_1 exdb035_w2_3_2 exdb035_w2_3_3 exdb035_w2_3_4 rabyear radage  if inw`wv'xt==1, result(raxphoneage)
replace raxphoneage = .h if exdb035_w2_1==2
replace raxphoneage = .l if exdb035_w2_2==2
replace raxphoneage = exdb035_w2_3_4 - rabyear if !mi(exdb035_w2_3_4) & !mi(rabyear) & (exdb035_w2_1==1 | (inlist(exdb035_w2_1,3,4) & exdb035_w2_2==1))
replace raxphoneage = radage - exdb035_w2_3_2  if !mi(exdb035_w2_3_2) & !mi(radage) & (exdb035_w2_1==1 | (inlist(exdb035_w2_1,3,4) & exdb035_w2_2==1))
replace raxphoneage = floor((dmonths - exdb035_w2_3_1)/12) if inrange(exdb035_w2_3_1,0,16) & !mi(dmonths) & (exdb035_w2_1==1 | (inlist(exdb035_w2_1,3,4) & exdb035_w2_2==1)) 
replace raxphoneage = exdb035_w2_3_3 if !mi(exdb035_w2_3_3) & (exdb035_w2_1==1 | (inlist(exdb035_w2_1,3,4) & exdb035_w2_2==1))
replace raxphoneage = radage if raxphoneage==(radage+1) & rabmonth > raxmonth & !mi(rabmonth) & !mi(raxmonth) & inw`wv'xt==1
replace raxphoneage = .i if ((raxphoneage > radage) | (raxphoneage < 0)) & !mi(raxphoneage) & !mi(radage) & inw`wv'xt==1 
label variable raxphoneage "raxphoneage: age r began to need help using the phone"


*wave2 respondent began needing help using the phone within final year
gen raxphoneb1y = .
missing raxphoneage radage raxyear exdb035_w2_3_1 exdb035_w2_3_2 exdb035_w2_3_3 exdb035_w2_3_4 if inw`wv'xt==1, result(raxphoneb1y)
replace raxphoneb1y = .h if raxphonehlp==0 & inw`wv'xt==1
replace raxphoneb1y = .l if exdb035_w2_2==2
replace raxphoneb1y = 0 if inrange(exdb035_w2_3_1,13,16) | ///
													inrange(exdb035_w2_3_2,2,22) | ///
													(((radage - exdb035_w2_3_3) > 1) & !mi(radage) & inrange(exdb035_w2_3_3,0,89)) | ///
													(((raxyear - exdb035_w2_3_4) > 1) & !mi(raxyear) & inrange(exdb035_w2_3_4,1922,2013)) 
replace raxphoneb1y = 1 if inrange(exdb035_w2_3_1,0,12) | ///
													inrange(exdb035_w2_3_2,0,1) | ///
													((((radage - exdb035_w2_3_3) == 0) | ((radage - exdb035_w2_3_3) == 1)) & !mi(radage) & inrange(exdb035_w2_3_3,0,89)) | ///
													((((raxyear - exdb035_w2_3_4) == 0) | ((raxyear - exdb035_w2_3_4) == 1)) & !mi(raxyear) & inrange(exdb035_w2_3_4,1922,2013))
replace raxphoneb1y = .i if raxphoneage==.i & inw`wv'xt==1
label variable raxphoneb1y "raxphoneb1y: r final help with using the phone started within year"
label values raxphoneb1y yesnocare


************Taking medications***********
*wave 2 respondent
gen raxmedhlp = .
missing exdb020_w2_1 if inw`wv'xt==1, result(raxmedhlp)
replace raxmedhlp = .t if exdb020_w2_1==3
replace raxmedhlp = .j if exdb020_w2_1==4
replace raxmedhlp = 0 if exdb020_w2_1==2
replace raxmedhlp = 1 if exdb020_w2_1==1
label variable raxmedhlp "raxmedhlp: someone helped r with medications final 3 months"
label values raxmedhlp yesnocare

gen raxmedage = .
missing exdb020_w2_2 exdb020_w2_3_1 exdb020_w2_3_2 exdb020_w2_3_3 exdb020_w2_3_4 rabyear radage  if inw`wv'xt==1, result(raxmedage)
replace raxmedage = .h if exdb020_w2_1==2
replace raxmedage = .l if exdb020_w2_2==2
replace raxmedage = exdb020_w2_3_4 - rabyear if !mi(exdb020_w2_3_4) & !mi(rabyear) & (exdb020_w2_1==1 | (inlist(exdb020_w2_1,3,4) & exdb020_w2_2==1))
replace raxmedage = radage - exdb020_w2_3_2  if !mi(exdb020_w2_3_2) & !mi(radage) & (exdb020_w2_1==1 | (inlist(exdb020_w2_1,3,4) & exdb020_w2_2==1))
replace raxmedage = floor((dmonths - exdb020_w2_3_1)/12) if inrange(exdb020_w2_3_1,0,22) & !mi(dmonths) & (exdb020_w2_1==1 | (inlist(exdb020_w2_1,3,4) & exdb020_w2_2==1)) 
replace raxmedage = exdb020_w2_3_3 if !mi(exdb020_w2_3_3) & (exdb020_w2_1==1 | (inlist(exdb020_w2_1,3,4) & exdb020_w2_2==1))
replace raxmedage = radage if raxmedage==(radage+1) & rabmonth > raxmonth & !mi(rabmonth) & !mi(raxmonth) & inw`wv'xt==1
replace raxmedage = .i if ((raxmedage > radage) | (raxmedage < 0)) & !mi(raxmedage) & !mi(radage) & inw`wv'xt==1 
label variable raxmedage "raxmedage: age r began to need help with medications"

*wave2 respondent began needing help with medications within final year
gen raxmedb1y = .
missing raxmedage radage raxyear exdb020_w2_3_1 exdb020_w2_3_2 exdb020_w2_3_3 exdb020_w2_3_4 if inw`wv'xt==1, result(raxmedb1y)
replace raxmedb1y = .h if raxmedhlp==0 & inw`wv'xt==1
replace raxmedb1y = .l if exdb020_w2_2==2
replace raxmedb1y = 0 if inrange(exdb020_w2_3_1,13,22) | ///
													inrange(exdb020_w2_3_2,2,12) | ///
													(((radage - exdb020_w2_3_3) > 1) & !mi(radage) & inrange(exdb020_w2_3_3,0,89)) | ///
													(((raxyear - exdb020_w2_3_4) > 1) & !mi(raxyear) & inrange(exdb020_w2_3_4,1989,2013)) 
replace raxmedb1y = 1 if inrange(exdb020_w2_3_1,0,12) | ///
													inrange(exdb020_w2_3_2,0,1) | ///
													((((radage - exdb020_w2_3_3) == 0) | ((radage - exdb020_w2_3_3) == 1)) & !mi(radage) & inrange(exdb020_w2_3_3,0,89)) | ///
													((((raxyear - exdb020_w2_3_4) == 0) | ((raxyear - exdb020_w2_3_4) == 1)) & !mi(raxyear) & inrange(exdb020_w2_3_4,1989,2013))
replace raxmedb1y = .i if raxmedage==.i & inw`wv'xt==1
label variable raxmedb1y "raxmedb1y: r final help with medications started within year"
label values raxmedb1y yesnocare


************Managing money***********
*wave 2 respondent
gen raxmoneyhlp = .
missing exdb019_w2_1 if inw`wv'xt==1, result(raxmoneyhlp)
replace raxmoneyhlp = .t if exdb019_w2_1==3
replace raxmoneyhlp = .j if exdb019_w2_1==4
replace raxmoneyhlp = 0 if exdb019_w2_1==2
replace raxmoneyhlp = 1 if exdb019_w2_1==1
label variable raxmoneyhlp "raxmoneyhlp: someone helped r manage money final 3 months"
label values raxmoneyhlp yesnocare

gen raxmoneyage = .
missing exdb019_w2_2 exdb019_w2_3_1 exdb019_w2_3_2 exdb019_w2_3_3 exdb019_w2_3_4 rabyear radage  if inw`wv'xt==1, result(raxmoneyage)
replace raxmoneyage = .h if exdb019_w2_1==2
replace raxmoneyage = .l if exdb019_w2_2==2
replace raxmoneyage = exdb019_w2_3_4 - rabyear if !mi(exdb019_w2_3_4) & !mi(rabyear) & (exdb019_w2_1==1 | (inlist(exdb019_w2_1,3,4) & exdb019_w2_2==1))
replace raxmoneyage = radage - exdb019_w2_3_2  if !mi(exdb019_w2_3_2) & !mi(radage) & (exdb019_w2_1==1 | (inlist(exdb019_w2_1,3,4) & exdb019_w2_2==1))
replace raxmoneyage = floor((dmonths - exdb019_w2_3_1)/12) if inrange(exdb019_w2_3_1,0,20) & !mi(dmonths) & (exdb019_w2_1==1 | (inlist(exdb019_w2_1,3,4) & exdb019_w2_2==1)) 
replace raxmoneyage = exdb019_w2_3_3 if !mi(exdb019_w2_3_3) & (exdb019_w2_1==1 | (inlist(exdb019_w2_1,3,4) & exdb019_w2_2==1))
replace raxmoneyage = radage if raxmoneyage==(radage+1) & rabmonth > raxmonth & !mi(rabmonth) & !mi(raxmonth) & inw`wv'xt==1
replace raxmoneyage = .i if ((raxmoneyage > radage) | (raxmoneyage < 0)) & !mi(raxmoneyage) & !mi(radage) & inw`wv'xt==1 
label variable raxmoneyage "raxmoneyage: age r began to need help managing money"


*wave2 respondent began needing help managing money within final year
gen raxmoneyb1y = .
missing raxmoneyage radage raxyear exdb019_w2_3_1 exdb019_w2_3_2 exdb019_w2_3_3 exdb019_w2_3_4 if inw`wv'xt==1, result(raxmoneyb1y)
replace raxmoneyb1y = .h if raxmoneyhlp==0 & inw`wv'xt==1
replace raxmoneyb1y = .l if exdb019_w2_2==2
replace raxmoneyb1y = 0 if inrange(exdb019_w2_3_1,13,20) | ///
													inrange(exdb019_w2_3_2,2,30) | ///
													(((radage - exdb019_w2_3_3) > 1) & !mi(radage) & inrange(exdb019_w2_3_3,0,89)) | ///
													(((raxyear - exdb019_w2_3_4) > 1) & !mi(raxyear) & inrange(exdb019_w2_3_4,1960,2013)) 
replace raxmoneyb1y = 1 if inrange(exdb019_w2_3_1,0,12) | ///
													inrange(exdb019_w2_3_2,0,1) | ///
													((((radage - exdb019_w2_3_3) == 0) | ((radage - exdb019_w2_3_3) == 1)) & !mi(radage) & inrange(exdb019_w2_3_3,0,89)) | ///
													((((raxyear - exdb019_w2_3_4) == 0) | ((raxyear - exdb019_w2_3_4) == 1)) & !mi(raxyear) & inrange(exdb019_w2_3_4,1960,2013))
replace raxmoneyb1y = .i if raxmoneyage==.i & inw`wv'xt==1
label variable raxmoneyb1y "raxmoneyb1y: r final help with managing money started within year"
label values raxmoneyb1y yesnocare

***began needing help with any iadl activities within final year***
*wave 2 respondent began needing help with iadl activities within final year
gen raxricareb = .
missing raxmealb1y raxshopb1y raxphoneb1y raxmedb1y raxmoneyb1y if inw`wv'xt==1, result(raxricareb) wave(`wv')
replace raxricareb = .l if (raxmealb1y==.l | raxshopb1y==.l | raxphoneb1y==.l | raxmedb1y==.l | raxmoneyb1y==.l) & inw`wv'xt==1
replace raxricareb = .h if (raxmealb1y==.h & raxshopb1y==.h & raxphoneb1y==.h & raxmedb1y==.h | raxmoneyb1y==.h) & inw`wv'xt==1
replace raxricareb = 0 if (raxmealb1y==0 | raxshopb1y==0 | raxphoneb1y==0 | raxmedb1y==0 | raxmoneyb1y==0) & inw`wv'xt==1
replace raxricareb = 1 if (raxmealb1y==1 | raxshopb1y==1 | raxphoneb1y==1 | raxmedb1y==1 | raxmoneyb1y==1) & inw`wv'xt==1
replace raxricareb = .i if (raxmealb1y==.i | raxshopb1y==.i | raxphoneb1y==.i | raxmedb1y==.i | raxmoneyb1y==.i) & inw`wv'xt==1
label variable raxricareb "raxricareb: r final help with any iadl started within year"
label values raxricareb yesnocare


**********Whether anyone helped with any of the IADLs**********
egen iadlsum = rowtotal(exdb022_w2_5_1_s1 - exdb022_w2_5_1_s66),m
egen moneysum = rowtotal(exdb022_w2_9_1_s1 - exdb022_w2_9_1_s66),m

gen raxricany = . 
replace raxricany = .m if inw`wv'xt==1 
replace raxricany = .l if (raxmealhlp==.l | raxshophlp==.l | raxphonehlp==.l | raxmedhlp==.l | raxmoneyhlp==.l) & inw`wv'xt==1
replace raxricany = 0 if (raxmealhlp==0 | raxshophlp==0 | raxphonehlp==0 | raxmedhlp==0 | raxmoneyhlp==0) & inw`wv'xt==1
replace raxricany = 1 if (raxmealhlp==1 | raxshophlp==1 | raxphonehlp==1 | raxmedhlp==1 | raxmoneyhlp==1) & inw`wv'xt==1
replace raxricany = 1 if (inrange(iadlsum,1,300) | inrange(moneysum,1,100)) & inw`wv'xt==1
label variable raxricany "raxricany: r received any care for IADLs"
label values raxricany yesnocare
drop iadlsum moneysum

**Drop temporary dmonths variable
drop dmonths

**************************
********EQUIPMENT*********
**************************

************Used walking equipment*********** (walking stick, travel device, manual wheelchair, electric wheelchair)
*wave 2 respondent
gen raxwalkre = 0
replace raxwalkre=.m if exdb029s1==. & exdb029s2==. & exdb029s3==. & exdb029s4==. & exdb029s5==. & exdb029s6==. & exdb029s7==.
replace raxwalkre=0 if exdb029s5==5 | exdb029s6==6 
replace raxwalkre=0 if exdb029s7==7
replace raxwalkre=1 if exdb029s1==1 | exdb029s2==2  | exdb029s3==3 | exdb029s4==4
label variable raxwalkre "raxwalkre: R Eqp-Walk final 3 months"
label values raxwalkre yesnocare


************Used toilet equipment*********** (catheter, toilet series)
*wave 2 respondent
gen raxtoilte = 0
replace raxtoilte=.m if exdb029s1==. & exdb029s2==. & exdb029s3==. & exdb029s4==. & exdb029s5==. & exdb029s6==. & exdb029s7==.
replace raxtoilte=0 if exdb029s1==1 | exdb029s2==2  | exdb029s3==3 | exdb029s4==4
replace raxtoilte=0 if exdb029s7==7
replace raxtoilte=1 if exdb029s5==5 | exdb029s6==6 
label variable raxtoilte "raxtoilte: R Eqp-Toilet final 3 months"
label values raxtoilte yesnocare



******ADDITIONAL ADLs and IADLs VARIABLES*** (RAXRACANY and RAXRICANY included in previous subsections)

*********Whether anyone helped with any of the ADLs or IADLs**********
gen raxrcany = .
replace raxrcany = .m if (raxracany==.m | raxricany==.m) & inw`wv'xt==1
replace raxrcany = .j if (raxracany==.j | raxricany==.j) & inw`wv'xt==1 
replace raxrcany = .t if (raxracany==.t | raxricany==.t) & inw`wv'xt==1
replace raxrcany = 0 if (raxracany==0 | raxricany==0) & inw`wv'xt==1
replace raxrcany = 1 if (raxracany==1 | raxricany==1) & inw`wv'xt==1
label variable raxrcany "raxrcany: r received any care for ADLs/IADLs"
label values raxrcany yesnocare

***began needing help with any adl or iadl activities within final year***
*wave 2 respondent began needing help with any adl or iadl activities within final year
gen raxrcareb = .
missing raxdressb1y raxbatheb1y raxeatb1y raxbedb1y raxtoiletb1y if inw`wv'xt==1, result(raxrcareb) wave(`wv')
replace raxrcareb = .m if (raxracareb==.m | raxricareb==.m) & inw`wv'xt==1
replace raxrcareb = .l if raxricareb==.l & inw`wv'xt==1
replace raxrcareb = .h if (raxracareb==.h | raxricareb==.h) & inw`wv'xt==1
replace raxrcareb = 0 if (raxracareb==0 | raxricareb==0) & inw`wv'xt==1
replace raxrcareb = 1 if (raxracareb==1 | raxricareb==1) & inw`wv'xt==1
replace raxrcareb = .i if (raxracareb==.i | raxricareb==.i) & inw`wv'xt==1
label variable raxrcareb "raxrcareb: r final help with any ADL/IADL started within year"
label values raxrcareb yesnocare




*******  WHO helped with ADLs and IADLs*******

******ADLs********

**Whether spouse (including ex-spouse) helped with ADLs
gen raxrascare = .
replace raxrascare = .m if raxracany==.m & inw`wv'xt==1
replace raxrascare = .h if raxracany==0 & inw`wv'xt==1
replace raxrascare = 0 if (exdb022_w2_1_1_s1==. & exdb022_w2_1_1_s2==. & ///
													 exdb022_w2_1_2_s1==. & exdb022_w2_1_2_s2==. & ///
													 exdb022_w2_1_3_s1==. & exdb022_w2_1_3_s2==.) & raxracany==1 & inw`wv'xt==1 
replace raxrascare = 1 if (exdb022_w2_1_1_s1==1 | exdb022_w2_1_1_s2==2 | ///
													 exdb022_w2_1_2_s1==1 | exdb022_w2_1_2_s2==2 | ///
													 exdb022_w2_1_3_s1==1 | exdb022_w2_1_3_s2==2) & raxracany==1 & inw`wv'xt==1
label variable raxrascare "raxrascare: r received informal care from spouse for ADLs"
label values raxrascare yesnocare


**Whether children, children's spouse, grandsons and granddaughters helped with ADLs
gen raxraccare = .
replace raxraccare = .m if raxracany==.m & inw`wv'xt==1
replace raxraccare = .h if raxracany==0 & inw`wv'xt==1
forvalues n = 7 / 56 {
	replace raxraccare = 0 if (exdb022_w2_1_1_s`n'==. & exdb022_w2_1_2_s`n'==. & exdb022_w2_1_3_s`n'==. & raxraccare==.) & raxracany==1 & inw`wv'xt==1
} 
replace raxraccare = 0 if (exdb022_w2_1_1_s60==. & exdb022_w2_1_1_s61==. & ///
													 exdb022_w2_1_2_s60==. & exdb022_w2_1_2_s61==. & ///
													 exdb022_w2_1_3_s60==. & exdb022_w2_1_3_s61==.) & raxracany==1 & inw`wv'xt==1
forvalues n = 7 / 56 {

  replace raxraccare = 1 if (exdb022_w2_1_1_s`n'==`n' | exdb022_w2_1_2_s`n'==`n' | exdb022_w2_1_3_s`n'==`n') & raxracany==1 & inw`wv'xt==1
} 
replace raxraccare = 1 if (exdb022_w2_1_1_s60==60 | exdb022_w2_1_1_s61==61 | ///
													 exdb022_w2_1_2_s60==60 | exdb022_w2_1_2_s61==61 | ///
													 exdb022_w2_1_3_s60==60 | exdb022_w2_1_3_s61==61) & raxracany==1 & inw`wv'xt==1
label variable raxraccare "raxraccare: r received informal care from kids/grandkids for ADLs"
label values raxraccare yesnocare


**Whether mother, father, mother-in-law, father-in-law, sibling, sibling of spouse, brother/sister-in-law, other relative helped with ADLs
gen raxrarcare = .
replace raxrarcare = .m if raxracany==.m & inw`wv'xt==1
replace raxrarcare = .h if raxracany==0 & inw`wv'xt==1
forvalues n = 3 / 6 {
	replace raxrarcare = 0 if (exdb022_w2_1_1_s`n'==. & exdb022_w2_1_2_s`n'==. & exdb022_w2_1_3_s`n'==. & raxrarcare==.) & raxracany==1 & inw`wv'xt==1
}
forvalues n = 57 / 59 {
	replace raxrarcare = 0 if (exdb022_w2_1_1_s`n'==. & exdb022_w2_1_2_s`n'==. & exdb022_w2_1_3_s`n'==. & raxrarcare==.) & raxracany==1 & inw`wv'xt==1
}
replace raxrarcare = 0 if (exdb022_w2_1_1_s62==. | exdb022_w2_1_2_s62==. | exdb022_w2_1_3_s62==.) & raxracany==1 & inw`wv'xt==1

forvalues n = 3 / 6 {
  replace raxrarcare = 1 if (exdb022_w2_1_1_s`n'==`n' | exdb022_w2_1_2_s`n'==`n' | exdb022_w2_1_3_s`n'==`n') & raxracany==1 & inw`wv'xt==1
}
forvalues n = 57 / 59 {
  replace raxrarcare = 1 if (exdb022_w2_1_1_s`n'==`n' | exdb022_w2_1_2_s`n'==`n' | exdb022_w2_1_3_s`n'==`n') & raxracany==1 & inw`wv'xt==1
}
replace raxrarcare = 1 if (exdb022_w2_1_1_s62==62 | exdb022_w2_1_2_s62==62 | exdb022_w2_1_3_s62==62) & raxracany==1 & inw`wv'xt==1
label variable raxrarcare "raxrarcare: r received informal care from relatives for ADLs"
label values raxrarcare yesnocare


**Whether other  (ONLY informal --> only other==66) helped with ADLs
gen raxrafcare = .
replace raxrafcare = .m if raxracany==.m & inw`wv'xt==1
replace raxrafcare = .h if raxracany==0 & inw`wv'xt==1
replace raxrafcare = 0 if (exdb022_w2_1_1_s66==. & exdb022_w2_1_2_s66==. & exdb022_w2_1_3_s66==. & raxrafcare==.) & raxracany==1 & inw`wv'xt==1
replace raxrafcare = 1 if (exdb022_w2_1_1_s66==66 | exdb022_w2_1_2_s66==66 | exdb022_w2_1_3_s66==66) & raxracany==1 & inw`wv'xt==1
label variable raxrafcare "raxrafcare: r received informal care from non-relatives for ADLs"
label values raxrafcare yesnocare


**Whether ANY informal help with ADLs
gen raxracaany = .
replace raxracaany = .m if (raxrascare == .m | raxraccare == .m | raxrarcare == .m | raxrafcare == .m) & inw`wv'xt==1
replace raxracaany = 0 if (raxrascare == .h | raxraccare == .h | raxrarcare == .h | raxrafcare == .h) & inw`wv'xt==1
replace raxracaany = 0 if (raxrascare == 0 | raxraccare == 0 | raxrarcare == 0 | raxrafcare == 0) & inw`wv'xt==1
replace raxracaany = 1 if (raxrascare == 1 | raxraccare == 1 | raxrarcare == 1 | raxrafcare == 1) & inw`wv'xt==1
label variable raxracaany "raxracaany: r received informal care for ADLs"
label values raxracaany yesnocare


**Whether ANY paid help with ADLs (paid helper, volunteer of employee of facility, employee of nursing home/hospice)
gen raxrafaany = .
replace raxrafaany = .m if raxracany==.m & inw`wv'xt==1
replace raxrafaany = 0 if raxracany==0 & inw`wv'xt==1
forvalues n = 63 / 65 {
	replace raxrafaany = 0 if (exdb022_w2_1_1_s`n'==. & exdb022_w2_1_2_s`n'==. & exdb022_w2_1_3_s`n'==. & raxrafaany==.) & raxracany==1 & inw`wv'xt==1
}
forvalues n = 63 / 65 {
  replace raxrafaany = 1 if (exdb022_w2_1_1_s`n'==`n' | exdb022_w2_1_2_s`n'==`n' | exdb022_w2_1_3_s`n'==`n') & raxracany==1 & inw`wv'xt==1
}
label variable raxrafaany "raxrafaany: r received formal care for ADLs" 
label values raxrafaany yesnocare




******IADLs********

**Whether spouse (including ex-spouse) helped with IADLs
gen raxriscare = .
replace raxriscare = .m if raxricany==.m & inw`wv'xt==1
replace raxriscare = .l if raxricany==.l & inw`wv'xt==1
replace raxriscare = .h if raxricany==0 & inw`wv'xt==1
replace raxriscare = 0 if (exdb022_w2_5_1_s1==. & exdb022_w2_5_1_s2==. & ///
													 exdb022_w2_5_2_s1==. & exdb022_w2_5_2_s2==. & ///
													 exdb022_w2_5_3_s1==. & exdb022_w2_5_3_s2==. & ///
													 exdb022_w2_5_4_s1==. & exdb022_w2_5_4_s2==. & ///
													 exdb022_w2_9_1_s1==. & exdb022_w2_9_1_s2==. & ///
													 exdb022_w2_9_2_s1==. & exdb022_w2_9_2_s2==.) & raxricany==1 & inw`wv'xt==1
replace raxriscare = 1 if (exdb022_w2_5_1_s1==1 | exdb022_w2_5_1_s2==2 | ///
													 exdb022_w2_5_2_s1==1 | exdb022_w2_5_2_s2==2 | ///
													 exdb022_w2_5_3_s1==1 | exdb022_w2_5_3_s2==2 | ///
													 exdb022_w2_5_4_s1==1 | exdb022_w2_5_4_s2==2 | ///
													 exdb022_w2_9_1_s1==1 | exdb022_w2_9_1_s2==2 | ///
													 exdb022_w2_9_2_s1==1 | exdb022_w2_9_2_s2==2) & raxricany==1 & inw`wv'xt==1
label variable raxriscare "raxriscare: r received informal care from spouse for IADLs"
label values raxriscare yesnocare


**Whether children, children's spouse, grandsons and granddaughters helped with IADLs 
gen raxriccare = .
replace raxriccare = .m if raxricany==.m & inw`wv'xt==1
replace raxriccare = .l if raxricany==.l & inw`wv'xt==1
replace raxriccare = .h if raxricany==0 & inw`wv'xt==1
forvalues n = 7 / 56 {
	replace raxriccare = 0 if (exdb022_w2_5_1_s`n'==. & exdb022_w2_5_2_s`n'==. & exdb022_w2_5_3_s`n'==.  & exdb022_w2_5_4_s`n'==. & ///
														 exdb022_w2_9_1_s`n'==. & exdb022_w2_9_2_s`n'==. & raxriccare==.) & raxricany==1 & inw`wv'xt==1
}
replace raxriccare = 0 if (exdb022_w2_5_1_s60==. & exdb022_w2_5_1_s61==. & ///
													 exdb022_w2_5_2_s60==. & exdb022_w2_5_2_s61==. & ///
													 exdb022_w2_5_3_s60==. & exdb022_w2_5_3_s61==. & ///
													 exdb022_w2_5_4_s60==. & exdb022_w2_5_4_s61==. & ///
													 exdb022_w2_9_1_s60==. & exdb022_w2_9_1_s61==. & ///
													 exdb022_w2_9_2_s60==. & exdb022_w2_9_2_s61==.) & raxricany==1 & inw`wv'xt==1
forvalues n = 7 / 56 {
  replace raxriccare = 1 if (exdb022_w2_5_1_s`n'==`n' | exdb022_w2_5_2_s`n'==`n' | exdb022_w2_5_3_s`n'==`n' | exdb022_w2_5_4_s`n'==`n' | ///
  													 exdb022_w2_9_1_s`n'==`n' | exdb022_w2_9_2_s`n'==`n') & raxricany==1 & inw`wv'xt==1
}
replace raxriccare = 1 if (exdb022_w2_5_1_s60==60 | exdb022_w2_5_1_s61==61 | ///
													 exdb022_w2_5_2_s60==60 | exdb022_w2_5_2_s61==61 | ///
													 exdb022_w2_5_3_s60==60 | exdb022_w2_5_3_s61==61 | ///
													 exdb022_w2_5_4_s60==60 | exdb022_w2_5_4_s61==61 | ///
													 exdb022_w2_9_1_s60==60 | exdb022_w2_9_1_s61==61 | ///
													 exdb022_w2_9_2_s60==60 | exdb022_w2_9_2_s61==61) & raxricany==1 & inw`wv'xt==1
label variable raxriccare "raxriccare: r received informal care from kids/grandkids for IADLs"
label values raxriccare yesnocare


**Whether mother, father, mother-in-law, father-in-law, sibling, sibling of spouse, brother/sister-in-law, other relative helped with IADLs 
gen raxrircare = .
replace raxrircare = .m if raxricany==.m & inw`wv'xt==1
replace raxrircare = .l if raxricany==.l & inw`wv'xt==1
replace raxrircare = .h if raxricany==0 & inw`wv'xt==1
forvalues n = 3 / 6 {
	replace raxrircare = 0 if (exdb022_w2_5_1_s`n'==. & exdb022_w2_5_2_s`n'==. & exdb022_w2_5_3_s`n'==. & exdb022_w2_5_4_s`n'==. & ///
														 exdb022_w2_9_1_s`n'==. & exdb022_w2_9_2_s`n'==.  & raxrircare==.) & raxricany==1 & inw`wv'xt==1
}
forvalues n = 57 / 59 {
	replace raxrircare = 0 if (exdb022_w2_5_1_s`n'==. & exdb022_w2_5_2_s`n'==. & exdb022_w2_5_3_s`n'==.  & exdb022_w2_5_4_s`n'==. & ///
														 exdb022_w2_9_1_s`n'==. & exdb022_w2_9_2_s`n'==.  & raxrircare==.) & raxricany==1 & inw`wv'xt==1
}
replace raxrircare = 0 if (exdb022_w2_5_1_s62==. | exdb022_w2_5_2_s62==. | exdb022_w2_5_3_s62==. | exdb022_w2_5_4_s62==. | ///
													 exdb022_w2_9_1_s62==. | exdb022_w2_9_2_s62==.) & raxricany==1 & inw`wv'xt==1

forvalues n = 3 / 6 {
  replace raxrircare = 1 if (exdb022_w2_5_1_s`n'==`n' | exdb022_w2_5_2_s`n'==`n' | exdb022_w2_5_3_s`n'==`n' | exdb022_w2_5_4_s`n'==`n' | ///
  													 exdb022_w2_9_1_s`n'==`n' | exdb022_w2_9_2_s`n'==`n') & raxricany==1 & inw`wv'xt==1
}
forvalues n = 57 / 59 {
  replace raxrircare = 1 if (exdb022_w2_5_1_s`n'==`n' | exdb022_w2_5_2_s`n'==`n' | exdb022_w2_5_3_s`n'==`n' | exdb022_w2_5_4_s`n'==`n' | ///
  													 exdb022_w2_9_1_s`n'==`n' | exdb022_w2_9_2_s`n'==`n') & raxricany==1 & inw`wv'xt==1
}
replace raxrircare = 1 if (exdb022_w2_5_1_s62==62 | exdb022_w2_5_2_s62==62 | exdb022_w2_5_3_s62==62  | exdb022_w2_5_4_s62==62 | ///
													 exdb022_w2_9_1_s62==62 | exdb022_w2_9_2_s62==62 ) & raxricany==1 & inw`wv'xt==1
label variable raxrircare "raxrircare: r received informal care from relatives for IADLs"
label values raxrircare yesnocare


**Whether other  (ONLY informal --> only other==66) helped with IADLs 
gen raxrifcare = .
replace raxrifcare = .m if raxricany==.m & inw`wv'xt==1
replace raxrifcare = .l if raxricany==.l & inw`wv'xt==1
replace raxrifcare = .h if raxricany==0 & inw`wv'xt==1
replace raxrifcare = 0 if (exdb022_w2_5_1_s66==. & exdb022_w2_5_2_s66==. & exdb022_w2_5_3_s66==.  & exdb022_w2_5_4_s66==. & ///
													 exdb022_w2_9_1_s66==. & exdb022_w2_9_2_s66==. & raxrifcare==.) & raxricany==1 & inw`wv'xt==1
replace raxrifcare = 1 if (exdb022_w2_5_1_s66==66 | exdb022_w2_5_2_s66==66 | exdb022_w2_5_3_s66==66 | exdb022_w2_5_4_s66==66 | ///
													 exdb022_w2_9_1_s66==66 | exdb022_w2_9_2_s66==66) & raxricany==1 & inw`wv'xt==1
label variable raxrifcare "raxrifcare: r received informal care from non-relatives for IADLs"
label values raxrifcare yesnocare


**Whether ANY informal help with IADLs
gen raxricaany = .
replace raxricaany = .m if (raxriscare == .m | raxriccare == .m | raxrircare == .m | raxrifcare == .m) & inw`wv'xt==1
replace raxricaany = .l if (raxriscare == .l | raxriccare == .l | raxrircare == .l | raxrifcare == .l) & inw`wv'xt==1
replace raxricaany = 0 if (raxriscare == .h | raxriccare == .h | raxrircare == .h | raxrifcare == .h) & inw`wv'xt==1
replace raxricaany = 0 if (raxriscare == 0 | raxriccare == 0 | raxrircare == 0 | raxrifcare == 0) & inw`wv'xt==1
replace raxricaany = 1 if (raxriscare == 1 | raxriccare == 1 | raxrircare == 1 | raxrifcare == 1) & inw`wv'xt==1
label variable raxricaany "raxricaany: r received informal care for IADLs"
label values raxricaany yesnocare


**Whether ANY paid help with IADLs (paid helper, volunteer of employee of facility, employee of nursing home/hospice) 
gen raxrifaany = .
replace raxrifaany = .m if raxricany==.m & inw`wv'xt==1
replace raxrifaany = .l if raxricany==.l & inw`wv'xt==1
replace raxrifaany = 0 if raxricany==0 & inw`wv'xt==1
forvalues n = 63 / 65 {
	replace raxrifaany = 0 if (exdb022_w2_5_1_s`n'==. & exdb022_w2_5_2_s`n'==. & exdb022_w2_5_3_s`n'==.  & exdb022_w2_5_4_s`n'==. & ///
														 exdb022_w2_9_1_s`n'==. & exdb022_w2_9_2_s`n'==.  & raxrifaany==.) & raxricany==1 & inw`wv'xt==1
}
forvalues n = 63 / 65 {
  replace raxrifaany = 1 if (exdb022_w2_5_1_s`n'==`n' | exdb022_w2_5_2_s`n'==`n' | exdb022_w2_5_3_s`n'==`n' | exdb022_w2_5_4_s`n'==`n' | ///
  													 exdb022_w2_9_1_s`n'==`n' | exdb022_w2_9_2_s`n'==`n') & raxricany==1 & inw`wv'xt==1
}
label variable raxrifaany "raxrifaany: r received formal care for IADLs"
label values raxrifaany yesnocare



******ADLs or IADLs********

**Whether spouse (including ex-spouse) helped with ADLs or IADLs
gen raxrscare = .
replace raxrscare = .m if (raxrascare == .m | raxriscare == .m) & inw`wv'xt==1
replace raxrscare = .l if raxriscare == .l & inw`wv'xt==1
replace raxrscare = .h if (raxrascare == .h | raxriscare == .h) & inw`wv'xt==1
replace raxrscare = 0 if (raxrascare == 0 | raxriscare == 0) & inw`wv'xt==1
replace raxrscare = 1 if (raxrascare == 1 | raxriscare == 1) & inw`wv'xt==1
label variable raxrscare "raxrscare: r received informal care from spouse for ADLs or IADLs"
label values raxrscare yesnocare


**Whether children, children's spouse, grandsons and granddaughters helped with ADLs or IADLs
gen raxrccare = .
replace raxrccare = .m if (raxraccare == .m | raxriccare == .m) & inw`wv'xt==1
replace raxrccare = .l if raxriccare == .l & inw`wv'xt==1
replace raxrccare = .h if (raxraccare == .h | raxriccare == .h) & inw`wv'xt==1
replace raxrccare = 0 if (raxraccare == 0 | raxriccare == 0) & inw`wv'xt==1
replace raxrccare = 1 if (raxraccare == 1 | raxriccare == 1) & inw`wv'xt==1
label variable raxrccare "raxrccare: r received informal care from kids/grandkids for ADLs and IADLs"
label values raxrccare yesnocare


**Whether mother, father, mother-in-law, father-in-law, sibling, sibling of spouse, brother/sister-in-law, other relative helped with ADLs or IADLs
gen raxrrcare = .
replace raxrrcare = .m if (raxrarcare == .m | raxrircare == .m) & inw`wv'xt==1
replace raxrrcare = .l if raxrircare == .l & inw`wv'xt==1
replace raxrrcare = .h if (raxrarcare == .h | raxrircare == .h) & inw`wv'xt==1
replace raxrrcare = 0 if (raxrarcare == 0 | raxrircare == 0) & inw`wv'xt==1
replace raxrrcare = 1 if (raxrarcare == 1 | raxrircare == 1) & inw`wv'xt==1
label variable raxrrcare "raxrrcare: r received informal care from relatives for ADLs or IADLs"
label values raxrrcare yesnocare


**Whether other  (ONLY informal --> only other==66) helped with ADLs or IADLs
gen raxrfcare = .
replace raxrfcare = .m if (raxrafcare == .m | raxrifcare == .m) & inw`wv'xt==1
replace raxrfcare = .l if raxrifcare == .l & inw`wv'xt==1
replace raxrfcare = .h if (raxrafcare == .h | raxrifcare == .h) & inw`wv'xt==1
replace raxrfcare = 0 if (raxrafcare == 0 | raxrifcare == 0) & inw`wv'xt==1
replace raxrfcare = 1 if (raxrafcare == 1 | raxrifcare == 1) & inw`wv'xt==1
label variable raxrfcare "raxrfcare: r received informal care from non-relatives for ADLs or IADLs"
label values raxrfcare yesnocare


**Whether ANY informal help with ADLs or IADLs
gen raxrcaany = .
replace raxrcaany = .m if (raxracaany == .m | raxricaany == .m) & inw`wv'xt==1
replace raxrcaany = .l if raxricaany == .l & inw`wv'xt==1
replace raxrcaany = 0 if (raxracaany == .h | raxricaany == .h) & inw`wv'xt==1
replace raxrcaany = 0 if (raxracaany == 0 | raxricaany == 0) & inw`wv'xt==1
replace raxrcaany = 1 if (raxracaany == 1 | raxricaany == 1) & inw`wv'xt==1
label variable raxrcaany "raxrcaany: r received informal care for ADLs or IADLs"
label values raxrcaany yesnocare


**Whether ANY paid help with ADLs or IADLs (paid helper, volunteer of employee of facility, employee of nursing home/hospice)
gen raxrfaany = .
replace raxrfaany = .m if (raxrafaany == .m | raxrifaany == .m) & inw`wv'xt==1
replace raxrfaany = .l if raxrifaany == .l & inw`wv'xt==1
replace raxrfaany = 0 if (raxrafaany == .h | raxrifaany == .h) & inw`wv'xt==1
replace raxrfaany = 0 if (raxrafaany == 0 | raxrifaany == 0) & inw`wv'xt==1
replace raxrfaany = 1 if (raxrafaany == 1 | raxrifaany == 1) & inw`wv'xt==1
label variable raxrfaany "raxrfaany: r received formal care for ADLs or IADLs"
label values raxrfaany yesnocare


**********************************************************************************

****drop Harmonized CHARLS variables***
drop `carext_w2_hcharls'

****drop CHARLS EOL Exit Interview variables***
drop `carext_w2_xt'



******************************************************************************************


********************************************************************************************************************
********************************************************************************************************************

***drop respondents not in the H_CHARLS
drop if in_charls != 1

***drop respondents not in exit data
drop if inw2xt!=1

****drop imputation variables
drop inw1 inw2 inw3 inw4 ragender radagecat_i in_charls

***drop unused cpindex values
drop c2014cpindex c2015cpindex c2016cpindex c2017cpindex c2018cpindex

***Update all value labels***
foreach v of var * {
	local vlabel : value label `v'
	if "`vlabel'" != "" {
		label define `vlabel' ///
			.r ".r:refuse" ///
			.m ".m:missing" ///
			.d ".d:dk", modify
	}
}

****define variable order
order       ID ///
			householdID ///
			hhid ///
			pnc ///
			pn ///
			ID_w? ///
			householdID_w? ///
			communityID ///
			inxt ///
			raxt ///
			inw?xt ///
			raxtiwm ///
			raxtiwy ///
			ralstcore ///
			ralstcorey ///
			raxprxy ///
			raxyear ///
			raxmonth ///
			raxdatef ///
			radage ///
			radagef ///
			radtoivwm ///
			radtoivwy ///
			radtoivwf ///
			radloc ///
			radexpec ///
			racod_c ///
			ragcod ///
			raddur ///
			raddurd ///
			radmarrp ///
			radlivnh ///
			///
			ralcancre ///
			raxcancrf ///
			raxcancr ///
			raxcancre ///
			rallunge ///
			raxlungf ///
			raxlung ///
			raxlunge ///
			ralhearte ///
			raxheartf ///
			raxheart ///
			raxhearte ///
			raxhrtatt ///
			ralstroke ///
			raxstrokf ///
			raxstrok ///
			raxstroke ///
			ralhibpe ///
			raxhibpe ///
			raldiabe ///
			raxdiabe ///
			raxmemry1m ///
			raxmemrye ///
			///
			raxhosp1y ///
			raxhsptim1y ///
			raxhspicu ///
			raxhsplfs ///
			raxhspkds ///
			raxhspanb ///
			radhospnit ///
			radhospnitd ///
			raxdoctor1m ///
			raxdoctim1m ///
			raxdrugs ///
			raxdentst1y ///
			raxdentim1y ///
			raxtotdoc1m ///
			raxtotdocf1m ///
			raxtothos1y  ///
			raxtothosf1y  ///
			raxtotdrug1y ///
			raxtotdrugf1y ///
			raxtotden1y ///
			raxtotdenf1y ///
			raxtotome1y_c ///
			raxtotomef1y_c ///
			raxtotmd1y_c ///
			raxtotmdf1y_c ///
			raxoopdoc1m ///
			raxoopdocf1m ///
			raxoophos1y  ///
			raxoophosf1y  ///	
			raxoopdrug1y ///
			raxoopdrugf1y ///
			raxoopden1y ///
			raxoopdenf1y ///
			raxoopome1y_c ///
			raxoopomef1y_c ///
			raxoopmd1y_c ///
			raxoopmdf1y_c ///
			raxhigov ///
			raxhipriv ///
			///
			ramprobgs ///
			ramprobage ///
			ramprobwrs ///
			///
			c200?cpindex ///
			c201?cpindex ///
			raxahown ///
			raxhomedis_c ///
			raxhomesp ///
			raxhomech ///
			raxhomerl ///
			raxhomeot ///
			raxhomein ///
			raxahous ///
			raxafhous ///
			raxarlesf ///
			raxafnas ///
			raxaffnas ///
			raxaphas ///
			raxafphas ///
			raxapen ///
			raxafpen ///
			raxapenlf ///
			raxafpenlf ///
			raxatotn ///
			raxaftotns ///
			raxaftotn ///
			raxatotb ///
			raxaftotb ///
			///
			raxchild ///
			raxchildf ///
			raxdchild ///
			raxdchildf ///
			raxgrchild ///
			raxggrchild ///
			///
			raxwork ///
			raxjlastm_c ///
			raxjlasty_c ///
		  raxfret_c ///
		  ///
		  raxdresshlp ///
			raxbathehlp ///
			raxeathlp ///
		  raxbedhlp ///
		  raxtoilethlp /// 
		  raxdressage ///
			raxbatheage ///
			raxeatage ///
		  raxbedage ///
		  raxtoiletage ///
		  raxdressb1y ///
			raxbatheb1y ///
			raxeatb1y ///
		  raxbedb1y ///
		  raxtoiletb1y ///
		  raxracareb /// 		  
		  raxwalkre ///
		  raxtoilte ///
		  raxmealhlp ///
		  raxshophlp ///
		  raxphonehlp ///
		  raxmedhlp ///
		  raxmoneyhlp ///
		  raxmealage ///
		  raxshopage ///
		  raxphoneage ///
		  raxmedage ///
		  raxmoneyage ///
		  raxmealb1y ///
		  raxshopb1y ///
		  raxphoneb1y ///
		  raxmedb1y ///
		  raxmoneyb1y ///
		  raxricareb ///
		  raxrcareb /// 
		  raxracany ///
		  raxracaany ///
		  raxrascare ///
		  raxraccare ///
		  raxrarcare ///
		  raxrafcare ///
		  raxrafaany ///
		  raxricany ///
		  raxricaany ///
		  raxriscare ///
		  raxriccare ///
		  raxrircare ///
		  raxrifcare ///
		  raxrifaany ///
		  raxrcany ///
		  raxrcaany ///
		  raxrscare ///
		  raxrccare ///
		  raxrrcare ///
		  raxrfcare ///
		  raxrfaany ///
		  ///
		  rawitwill_c ///
			rawitwill ///
			rawillsp ///
			rawillcg ///
			rawillrl ///
			rawillot ///
			rawillin ///
			rawillfl ///
			rabnfcrsp ///
			rabnfcrcg ///
			rabnfcrrl ///
			rabnfcrot ///
			rabnfcrin ///
			raxfuneral ///
			raxfuneralf ///
			raxburial ///
			raxburialf ///
			radexpense_c ///
			radexpensef_c ///
			radrecfun ///
			radrecfunf ///
			raxlifeins ///
			raxlfinsv ///
			raxlfinsvf 
											
***final sort
sort ID

***compress dataset
compress	

***add label
label data "Harmonized CHARLS EOL Ver.A"

***add notes
notes drop _dta
note: Harmonized CHARLS EOL Ver.A
note: created May 2022 as part of the Gateway to Globabl Aging Data (www.g2aging.org)
note: see Harmonized CHARLS EOL codebook for more information

***remove unsued value lables
labelbook, problems
label drop `r(notused)'

***save output dataset
save "`data'/H_CHARLS_EOL_a", replace
